Interfacing Python To MySQL
Interfacing Python To MySQL
To MySQL
Steps required to establish Python to MySQL
connectivity
import mysql.connector
mysql.connector.connect()
con_obj.is_connected()
con_obj.cursor()
cursor_obj.execute()
Read operation
Fetchone()
Fetchmany()
Fetchall()
rowcount
CBSE Sample Question 1
Q1. Kabir wants to write a program in Python to insert the following record in the
table named Student in MYSQL database, SCHOOL:
rno(Roll number )- integer
name(Name) – string
DOB (Date of birth) – Date
Fee – float
The values of fields rno, name, DOB and fee has to be accepted from
the user. Help Kabir to write the program in Python.
Program
import mysql.connector as ms
con=ms.connect(host='localhost',user='root',passwd='tiger',database='sample2023')
mycursor=ms.cursor()
rno=int(input('Enter Roll Number:'))
name=input('Enter name:'))
DOB=input('Enter date of birth:')
fee=float(input('Enter fee:'))
query="INSERT into student values({},'{}',{})".format(rno,name,DOB,fee)
mycursor.execute(query)
con.commit()
print("Data added successfully")
con.close()
Sample Question 2
Kabir, now wants to display the records of students whose fee is more than 5000. Help Kabir to
write the program in Python.
Program :
import mysql.connector as ms
con=ms.connect(host='localhost',user='root',passwd='tiger',database='sample
2023')
mycursor=ms.cursor()
query=SELECT * from student where fee>{}.format(5000)
mycursor.execute(query)
data=mycursor.fetchall()
for rec in data:
print(rec)
Home work
Q1. Consider a database ‘company’ that has a table ‘emp’ that sores
details of employees. Write a mySQL Python connectivity program to
retrieve data for employees with IDs less than 10.
Slip Test
1. _______ method returns only one row from the result set in the form
of a tuple containing a record.
2. rowcount is a read only attribute(True/False).
3. The set of records retrieved after executing an SQL query over an
established connection is called ________.
4. Which command is used for cleaning up the environment?
5. To reflect the changes done in the database permanently, you need
to use _____ method.
Thank you