Computer Science
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()
Python MySQL
3 Likes
Answer
Table category
id | name |
---|---|
1 | abc |
2 | pqr |
3 | xyz |
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.
Answered By
1 Like
Related Questions
What are the steps to connect to a database from within a Python application ?
Write code to connect to a MySQL database namely School and then fetch all those records from table Student where grade is ' A' .
Explain what the following query will do ?
import mysql.connector db = mysql.connector.connect(....) cursor = db.cursor() person_id = input("Enter required person id") lastname = input("Enter required lastname") db.execute("INSERT INTO staff (person_id, lastname) VALUES ({}, '{}')".format(person_id, lastname)) db.commit() db.close()
Explain what the following query will do ?
import mysql.connector db = mysql.connector.connect(....) cursor = db.cursor() db.execute("SELECT * FROM staff WHERE person_id in {}".format((1, 3, 4))) db.commit() db.close()