Computer Science
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()
Python MySQL
1 Like
Answer
This Python script uses the mysql.connector
package to connect to MySQL database. Then it prompts users for person ID and last name, inserts these values into the 'staff' table, using the INSERT INTO SQL
statement. After that, it executes the SQL query using the db.execute method. The changes made by the query are then committed to the database using db.commit()
, ensuring that the changes are saved permanently. Finally, db.close()
closes the database connection, ending the Python interface with the MySQL database.
Answered By
3 Likes
Related Questions
Write code to connect to a MySQL database namely School and then fetch all those records from table Student where grade is ' A' .
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()
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()
Design a Python application that fetches all the records from Pet table of menagerie database.