Interface Python with MySQL
1. Stablish a connection to MySQL Database:
import mysql.connector
mycon=mysql.connector.connect(host="localhost", user="root", database="emp_info", password="root")
2. Check Connection:
if mycon.is_connected( ):
print("Connected")
else:
print("Not Connect")
3. Create MySQL Table:
tc="create table emp (id integer primary key,name char(20),city char(15))"
cur=mycon.cursor( )
cur.execute(tc)
mycon.commit( )
print("table Created")
4. Insert data in MySQL Table:
i="insert into emp (id,name,city,Salary) values(%s,%s,%s,%s)"
val=a,b,c,d
cur=mycon.cursor( )
cur.execute(i,val)
mycon.commit( )
print("Insert Data")
OR
i="insert into emp (id,name,city,Salary) values({},'{}','{}',{})".format(a,b,c,d)
cur=mycon.cursor( )
cur.execute(i)
mycon.commit( )
print("Insert Data")
5. Alter data in MySQL Table:
a="alter table emp add Salary integer not null"
cur=mycon.cursor( )
cur.execute(a)
mycon.commit( )
print("Alter Successfully")
6. Delete data from MySQL Table:
d="delete from emp where id=555"
cur=mycon.cursor( )
cur.execute(d)
mycon.commit( )
print("Data Deleted")
BY: FARAH ARIF 1
7. Update data in MySQL Table:
u="update emp set Salary=20000 where city='Gonda'"
cur=mycon.cursor( )
cur.execute(u)
mycon.commit( )
print("Updation Done")
OR
u1="update emp set Salary=25000 where name='Anil Soni'"
cur=mycon.cursor( )
cur.execute(u1)
mycon.commit( )
print("Update successfully")
8. Create a Cursor Instance:
cur=mycon.cursor( )
9. Execute MySQL Query:
cur.execute("select * from emp")
mycon.commit( )
10. fetchall( ) method:
This method will return all the rows from the resultset in the form of a tuple.
data= cursor.fetchall( )
for a in data:
print(a)
11. fetchone( ) method:
This method will return only one row from the resultset in the form of a tuple.
data= cursor.fetchone( )
12. fetchmany( ) method:
This method will return only the n number of rows from the resultset in the form of a tuple.
data= cursor.fetchmany(5)
for a in data:
print(a)
13. rowcount( ) method:
count=cursor.rowcount
BY: FARAH ARIF 2