Example 1: python project with database connectivity
import mysql.connector as MC
try:
Con_o = MC.connect(host="localhost",user="root",passwd="sidspc12345",database="mydb")
if Con_o.is_connected():
print("Connection established successfully")
except Exception as E:
print("Connection Failed !")
print("ERROR : ",e)
Cur = Con_o.cursor()
Cur.execute("select * from students where Percentage>= 95")
data = Cur.fetchall()
for row in data:
print(row)
Con_o.commit()
st = "INSERT INTO students(Roll,Name,Sex,Stream,Phone,Address,Maths,Science,SST,English,Hindi) values({},'{}','{}','{}',{},'{}',{},{},{},{},{})".format(11021,'Siddharth','M','S',7002744892,'Second link road Silchar',100,100,100,94,88)
Cur.execute(st)
Con_o.commit()
Cur.execute("select * from students")
data = Cur.fetchall()
for row in data:
print(row)
Con_o.close()
Example 2: connect python to mysql
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
port = 8888,
database='whatever db you want'
)
print(mydb)
Example 3: mysql connection python
from sqlalchemy import types, create_engine
import pymysql
try:
conn = create_engine('mysql+pymysql://user:pass@IP/database_name')
print("MySQL Connection Sucessfull!!!!!!!!!!!")
except Exception as err:
print("MySQL Connection Failed !!!!!!!!!!!")
print(err)