Interface Python with MySQL
1. Stablish a connection to MySQL Database:
import [Link]
mycon=[Link](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=[Link]( )
[Link](tc)
[Link]( )
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=[Link]( )
[Link](i,val)
[Link]( )
print("Insert Data")
OR
i="insert into emp (id,name,city,Salary) values({},'{}','{}',{})".format(a,b,c,d)
cur=[Link]( )
[Link](i)
[Link]( )
print("Insert Data")
5. Alter data in MySQL Table:
a="alter table emp add Salary integer not null"
cur=[Link]( )
[Link](a)
[Link]( )
print("Alter Successfully")
6. Delete data from MySQL Table:
d="delete from emp where id=555"
cur=[Link]( )
[Link](d)
[Link]( )
print("Data Deleted")
BY: FARAH ARIF 1
7. Update data in MySQL Table:
u="update emp set Salary=20000 where city='Gonda'"
cur=[Link]( )
[Link](u)
[Link]( )
print("Updation Done")
OR
u1="update emp set Salary=25000 where name='Anil Soni'"
cur=[Link]( )
[Link](u1)
[Link]( )
print("Update successfully")
8. Create a Cursor Instance:
cur=[Link]( )
9. Execute MySQL Query:
[Link]("select * from emp")
[Link]( )
10. fetchall( ) method:
This method will return all the rows from the resultset in the form of a tuple.
data= [Link]( )
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= [Link]( )
12. fetchmany( ) method:
This method will return only the n number of rows from the resultset in the form of a tuple.
data= [Link](5)
for a in data:
print(a)
13. rowcount( ) method:
count=[Link]
BY: FARAH ARIF 2