Python Interface - with mysql connector
Python Interface - with mysql connector
MYSQL CONNECTOR
Python mySql connectivity
• Connect mysql connector to python idle with the following command:
pip install mysql-connector
EXECUTE A QUERY
con=mysql.connector.connect(host=<hostname> ,
user = <username>,
pwd = <password>,
database = <database name>
• Syntax: cursorobject=cursorobject.connect()
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",pa
ssword="root",database="abc")
cur=con.cursor()
cur.execute("select * from emp")
data=cur.fetchall()
print(data)
• cursor.fetchall() : Returns all the records from the file in a tuple form
• cursor.fetchone(): It will return one record from the result set as a tuple
Note: first time it will fetch first record, next time it will fetch second record
Note: After all the process of your program, in this final step you need to close the application
with con.close()
Parameterized queries
import mysql.connector as a
con=a.connect(host="localhost",user="root",password="root",database="abc")
print("database connected and created successfully")
cur=con.cursor()
cur.execute("create table faculty(fno int, fname varchar(30), fsal float)")
print("database table faculty created")
fno=int(input("enter faculty number"))
fname=input("enter faculty name")
fsal=input("enter faculty salary")
query="insert into faculty values({},'{}',{})".format(fno,fname,fsal))
cur.execute(query)
print("row inserted successfully")
con.commit()
CREATING DATABASE TABLE AND INSERTING VALUES
import mysql.connector as a
con=a.connect(host="localhost",user="root",password="root",database="abc")
print("database connected and created successfully")
cur=con.cursor()
#cur.execute("create table faculty(fno int, fname varchar(30), fsal float)")
print("database table faculty created")
while True:
fno=int(input("enter faculty number"))
fname=input("enter faculty name")
fsal=input("enter faculty salary")
query="insert into faculty values({},'{}',{})".format(fno,fname,fsal)
cur.execute(query)
print("row inserted successfully")
con.commit()
ch=input("do you want to continue, press Y or N")
if ch=='n' or ch=='N':
break