Page 4 - Interface Python With SQL
P. 4
database='practice',user='root',password='1234')
cursor=db.cursor()
cursor.execute("select * from employee")
data=cursor.fetchmany(5)
for row in data:
print(row)
count=cursor.rowcount
print(count, "number of rows extracted")
fetchone()
import mysql.connector as sqlctr
db = sqlctr.connect(host='localhost',user='root',\
password='1234', database='practice')
cursor=db.cursor()
cursor.execute("select * from employee")
while True:
data=cursor.fetchone()
if data==None:
break
print(data)
count=cursor.rowcount
print(count, "number of rows extracted")
Clean up the environment
<connection object>.close()
will close the connection and will release the resources occupied.
pymysql
mysql.connector it is (library) made available by Oracle (owns MySQL)
pymysql this library is made available by Python
Working
1) Start Python
2) Import pymysql by: import pymysql
3) Connect to MySQL database by:
<connection>=pymysql.connect("localhost", <username>,
<password>, <database name>)
Program using pymysql
import pymysql as pym
db = pym.connect('localhost', 'root', '1234', 'practice')
cursor=db.cursor()
cursor.execute("select * from employee")
data=cursor.fetchall()
for row in data:
print(row)
count=cursor.rowcount
print(count, "number of rows")