π Interface of Python with SQL Quiz β Class 12 Computer Science (Code 083)
Practice 20 CBSE Class 12 Computer Science (Code 083) MCQs on connecting Python with an SQL database β connect(), cursor(), execute(), commit(), fetchone(), fetchall(), rowcount, performing INSERT/UPDATE/DELETE queries via a cursor, using %s placeholders safely, error handling, and closing connections.
Every method’s behaviour below has been verified against Python’s DB-API. This set includes 2 board-style predict-the-output questions with full working code. Tap any question to reveal the answer with a clear explanation.
π Connecting to SQL
What does the connect() function do when working with Python and SQL databases?
- Connects Python to the internet
- Establishes a connection to an SQL database
- Connects Python modules
- Connects Python to external APIs
Show Answer & Explanation
β Answer: (b) Establishes a connection to an SQL database
connect() (e.g. mysql.connector.connect(host=..., user=..., password=..., database=...)) opens a live connection to an SQL database server, which your program then uses for all further queries.
π±οΈ Cursor Object
Which function is used to create a cursor object when interacting with an SQL database in Python?
- create_cursor()
- make_cursor()
- cursor()
- generate_cursor()
Show Answer & Explanation
β Answer: (c) cursor()
You call .cursor() on an existing connection object (e.g. mycursor = mydb.cursor()) to get a cursor β the object actually used to execute SQL commands and fetch results.
βΆοΈ execute()
In Python, what is the purpose of the execute() method when working with an SQL database?
- Executes SQL queries
- Defines a new table
- Imports data into Python
- Initiates a database connection
Show Answer & Explanation
β Answer: (a) Executes SQL queries
cursor.execute(query) runs the given SQL query string against the connected database β this is the core method for sending any SELECT, INSERT, UPDATE, or DELETE statement.
πΎ commit()
How is data committed (permanently saved) to an SQL database using Python?
- commit()
- apply()
- save()
- finalize()
Show Answer & Explanation
β Answer: (a) commit()
connection.commit() permanently saves any changes made by INSERT, UPDATE, or DELETE statements. Without calling it, those changes may be lost or rolled back once the connection closes.
1οΈβ£ fetchone()
Which method retrieves the next single row of a query result set in Python?
- fetchrow()
- fetchnext()
- fetchone()
- fetchrowset()
Show Answer & Explanation
β Answer: (c) fetchone()
cursor.fetchone() returns the next unread row from the result set as a tuple, or None if there are no more rows left.
β INSERT Queries
How do you perform an INSERT query using a cursor in Python?
- insert_query()
- execute_insert()
- execute(“INSERT …”)
- add_record()
Show Answer & Explanation
β Answer: (c) execute(“INSERT …”)
There’s no special βinsertβ method β you simply pass a standard SQL INSERT statement as a string into execute(), just like any other query, e.g. cursor.execute("INSERT INTO Students VALUES (%s, %s, %s)", data).
π fetchall()
What does the fetchall() method do in Python when working with an SQL database?
- Fetches the first row of the result set
- Fetches all the rows of the result set as a list of tuples
- Fetches the last row of the result set
- Fetches a specific row based on a condition
Show Answer & Explanation
β Answer: (b) Fetches all the rows of the result set as a list of tuples
cursor.fetchall() retrieves every remaining row from the result set at once, returning them as a list of tuples β one tuple per row.
π’ rowcount
How can you check the number of rows affected by the last executed query in Python?
- cursor.rowcount (accessed as a property, WITHOUT parentheses)
- rowcount()
- get_rowcount()
- rows_affected()
Show Answer & Explanation
β Answer: (a) cursor.rowcount (accessed as a property, WITHOUT parentheses)
cursor.rowcount is a property, not a method β you read it directly, without calling it like a function. (This question is corrected from a version that showed it as rowcount() with parentheses, which is actually a syntax error since rowcount takes no arguments and isn’t callable at all.)
1οΈβ£ fetchone()
What is the purpose of the fetchone() method in Python when working with an SQL database?
- Fetches ALL rows of the result set at once
- Fetches only the LAST row of the result set
- Fetches the NEXT unread row of the result set (only the first row if called immediately after execute())
- Fetches a row only if a specific WHERE condition is separately re-applied
Show Answer & Explanation
β Answer: (c) Fetches the NEXT unread row of the result set (only the first row if called immediately after execute())
fetchone() always returns the next unread row β it happens to be the first row only if it’s the very first call after execute(). Calling it again fetches the row after that, and so on, until it returns None. (This question is refined from a version that simply said βfetches the first rowβ, which is only true the first time it’s called.)
βοΈ UPDATE Queries
How do you perform an UPDATE query using a cursor in Python?
- cursor_update()
- execute(“UPDATE …”)
- update_record()
- modify_query()
Show Answer & Explanation
β Answer: (b) execute(“UPDATE …”)
Just like INSERT, an UPDATE statement is simply passed as a string to execute(): cursor.execute("UPDATE Students SET Marks = 90 WHERE RollNo = 1"), followed by commit() to save the change.
π‘οΈ Parameterized Queries
What is the purpose of using the %s format specifier when writing SQL queries in Python (with mysql.connector)?
- It’s purely decorative and has no functional effect
- It acts as a placeholder for values, letting you safely pass parameters into a query and helping prevent SQL injection
- It only works with numeric data types
- It converts the query into a SELECT statement automatically
Show Answer & Explanation
β Answer: (b) It acts as a placeholder for values, letting you safely pass parameters into a query and helping prevent SQL injection
%s is a placeholder in the query string β the actual values are passed separately as a tuple, e.g. cursor.execute("INSERT INTO Students VALUES (%s, %s, %s)", (1, "Riya", 85)). This keeps user input separate from the SQL command itself, which is the standard defense against SQL injection attacks.
π‘οΈ Parameterized Queries
Besides using %s placeholders, what is another common way to build a query string with values in Python?
- Using the format() method or f-strings to insert values directly into the query text
- Only %s placeholders exist; there is no alternative
- Using the print() function
- Using the input() function
Show Answer & Explanation
β Answer: (a) Using the format() method or f-strings to insert values directly into the query text
You can also build the query text using str.format() or f-strings before passing it to execute(). However, unlike %s placeholders (which mysql.connector escapes safely), directly formatting raw values into a string is more vulnerable to SQL injection if the values come from untrusted user input.
π Closing Connections
Why is it important to close both the cursor and the connection after finishing database operations in Python?
- It’s not actually necessary; Python handles this entirely automatically with no downside to skipping it
- To release database resources and connections properly, preventing resource leaks
- To permanently delete all data in the database
- To automatically commit any uncommitted changes
Show Answer & Explanation
β Answer: (b) To release database resources and connections properly, preventing resource leaks
Calling cursor.close() and connection.close() frees up the resources (like the open connection slot on the database server) that were being used β leaving connections open unnecessarily can eventually exhaust the database’s connection limit.
π§― Error Handling
What is a recommended practice when performing database operations that might fail, such as a connection error or a bad query?
- Ignore all errors completely and let the entire program crash
- Wrap the database operations in a try-except block to handle potential errors gracefully
- Never use commit(), so errors can’t occur
- Always restart the entire program after any single query
Show Answer & Explanation
β Answer: (b) Wrap the database operations in a try-except block to handle potential errors gracefully
Wrapping database code in try-except lets you catch connection failures, invalid queries, or constraint violations gracefully β showing a helpful message or retrying, instead of letting the whole program crash.
π Connecting to SQL
Which of the following parameters are typically required when calling connect() to link Python with a MySQL database?
- Only the database name
- host, user, password, and database (or similar connection details)
- Only a username and a query string
- No parameters are ever required
Show Answer & Explanation
β Answer: (b) host, user, password, and database (or similar connection details)
A typical connection call looks like mysql.connector.connect(host="localhost", user="root", password="pass", database="school") β specifying where the server is, who is connecting, their credentials, and which database to use.
β Board-Style Programs
What does the following program do, assuming the Students table already has columns (RollNo, Name, Marks)?
data = (1, "Riya", 85)
cursor.execute("INSERT INTO Students VALUES (%s, %s, %s)", data)
mydb.commit()
print(cursor.rowcount, "record inserted.")- It only prepares the query text but never actually inserts anything into the database
- It inserts one new row (1, ‘Riya’, 85) into the Students table, permanently saves it, and reports 1 record inserted
- It raises an error, since %s cannot be used for text values like ‘Riya’
- It inserts three separate rows, one for each value in the tuple
Show Answer & Explanation
β Answer: (b) It inserts one new row (1, ‘Riya’, 85) into the Students table, permanently saves it, and reports 1 record inserted
The %s placeholders are filled in order by the values in the data tuple, inserting exactly one new row. commit() makes that change permanent, and cursor.rowcount confirms 1 row was affected.
β Board-Style Programs
What does the following program print, assuming the Students table contains three rows: (1,’Riya’,90), (2,’Aman’,78), (3,’Kabir’,92)?
cursor.execute("SELECT Name, Marks FROM Students")
results = cursor.fetchall()
for row in results:
print(row)- Only the first row is printed, then the loop stops
- All three rows are printed, one tuple per line, in the order they were retrieved
- Nothing is printed, since fetchall() cannot be used with a for loop
- An error occurs, since results is not iterable
Show Answer & Explanation
β Answer: (b) All three rows are printed, one tuple per line, in the order they were retrieved
fetchall() returns a list of all matching rows as tuples. Looping over that list with for row in results: prints each tuple one at a time: ('Riya', 90), then ('Aman', 78), then ('Kabir', 92) β a very common pattern for displaying query results.
πΎ commit()
What happens if you execute an INSERT or UPDATE query but FORGET to call commit() afterward?
- The change is guaranteed to be saved permanently regardless
- The change may not be permanently saved to the database β it can be lost once the connection closes (depending on the database’s autocommit setting)
- Python raises an immediate SyntaxError
- The query itself will fail to execute at all
Show Answer & Explanation
β Answer: (b) The change may not be permanently saved to the database β it can be lost once the connection closes (depending on the database’s autocommit setting)
Without commit(), changes made through execute() for INSERT/UPDATE/DELETE may exist only in the current transaction and can be lost if the connection closes or the transaction is rolled back β this is exactly why commit() is a critical, easy-to-forget step in every write operation.
βοΈ fetchone() and fetchall()
What is the key difference between fetchone() and fetchall() when reading query results?
- They are functionally identical in every way
- fetchone() returns just the next single row (or None); fetchall() returns every remaining row at once, as a list of tuples
- fetchall() can only be used with SELECT * queries
- fetchone() automatically loops through all rows internally
Show Answer & Explanation
β Answer: (b) fetchone() returns just the next single row (or None); fetchall() returns every remaining row at once, as a list of tuples
fetchone() pulls one row at a time β useful when you only need the first match or want to process rows one by one without loading everything into memory. fetchall() grabs everything remaining in one go, convenient for smaller result sets you want as a complete list.
ποΈ DELETE Queries
How do you perform a DELETE query using a cursor in Python?
- delete_record()
- cursor.remove()
- execute(“DELETE FROM table WHERE condition”)
- drop_row()
Show Answer & Explanation
β Answer: (c) execute(“DELETE FROM table WHERE condition”)
Just like INSERT and UPDATE, a DELETE statement is passed as a plain SQL string to execute(): cursor.execute("DELETE FROM Students WHERE RollNo = %s", (3,)), followed by commit() to make the deletion permanent.
