CBSE Class 12 Computer Science Question 41 of 46

Interface Python with MySQL — Question 3

Back to all questions
3
Question

Question 3

Predict the output of the following code :

import mysql.connector
db = mysql.connector.connect(....)
cursor = db.cursor()
sql1 = "update category set name = '%s' WHERE ID = %s" % ('CSS',2)
cursor.execute(sql1)
db.commit()
print("Rows affected:", cursor.rowcount)
db.close()
Answer

Table category

idname
1abc
2pqr
3xyz
Output
Rows affected: 1
SELECT * FROM category ;
+----+------+
| id | name |
+----+------+
|  1 | abc  |
|  2 | CSS  |
|  3 | xyz  |
+----+------+
Explanation

This Python script uses the mysql.connector module to connect to MySQL database. It updates the 'name' field in the 'category' table where ID is 2 to 'CSS'. The cursor.execute() method executes the SQL query, db.commit() commits the changes, and cursor.rowcount gives the number of affected rows. Finally, db.close() closes the database connection, ending the Python interface with the MySQL database.