Python – MySQL Connectivity Revision Questions with
Solutions
1. Short Answer – Theory
Q1. Write the steps to connect Python with a MySQL database.
Answer:
1. Import the module
2. import mysql.connector
3. Establish a connection
4. mycon = mysql.connector.connect(host='localhost', user='root',
passwd='xxxx', database='school')
5. Create a cursor object
6. cursor = mycon.cursor()
7. Execute SQL queries
8. cursor.execute("SELECT * FROM student")
9. Fetch results (if required)
10. data = cursor.fetchall()
11. Close connection
12. mycon.close()
2. Output Prediction
Q2.
import mysql.connector as sql
con = sql.connect(host="localhost", user="root", passwd="1234",
database="school")
cur = con.cursor()
cur.execute("SELECT Name, Marks FROM student WHERE Marks > 80")
for row in cur.fetchall():
print(row[0], "-", row[1])
If the table student has:
RollNo Name Marks
1 Amit 85
2 Priya 78
3 Rohan 92
Output:
Amit - 85
Rohan - 92
3. Error Finding
Q3. Identify and correct the error:
import mysql.connector
mycon = mysql.connector.connect("localhost", "root", "1234", "school")
Answer:
connect() should use keyword arguments:
mycon = mysql.connector.connect(host="localhost", user="root",
passwd="1234", database="school")
4. Query Execution
Q4. Write a Python program to:
Connect to a MySQL database school
Insert a record into table student(RollNo INT, Name VARCHAR(30), Marks INT)
Commit and close the connection
Answer:
import mysql.connector
mycon = mysql.connector.connect(host="localhost", user="root",
passwd="1234", database="school")
cur = mycon.cursor()
qry = "INSERT INTO student VALUES (%s, %s, %s)"
data = (4, 'Neha', 88)
cur.execute(qry, data)
mycon.commit()
print("Record inserted successfully")
mycon.close()
5. Fetching Data – Board Style
Q5. Write a Python program to display the names of students scoring between 70 and 90
from student table.
Answer:
import mysql.connector
mycon = mysql.connector.connect(host="localhost", user="root",
passwd="1234", database="school")
cur = mycon.cursor()
cur.execute("SELECT Name FROM student WHERE Marks BETWEEN 70 AND 90")
for row in cur.fetchall():
print(row[0])
mycon.close()
6. Board-Level Integrated Question
Q6. A table EMPLOYEE has the following data:
EID NAME SALARY
101 Rahul 45000
102 Meena 52000
103 Arjun 48000
Write a Python program to:
1. Connect to MySQL
2. Display the details of employees with salary > 48000
Answer:
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="1234",
database="company")
cur = con.cursor()
cur.execute("SELECT * FROM EMPLOYEE WHERE SALARY > 48000")
for row in cur.fetchall():
print(row)
con.close()
Output:
(102, 'Meena', 52000)