Interface of python with SQL Quiz Class 12

πŸ”— 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πŸ–±οΈ Cursor Object▢️ execute()πŸ’Ύ commit()πŸ“‹ fetchone/fetchallπŸ”’ rowcountπŸ›‘οΈ Parameterized Queries⭐ Board-Style Programs
Q1
πŸ”— Connecting to SQL

What does the connect() function do when working with Python and SQL databases?

  1. Connects Python to the internet
  2. Establishes a connection to an SQL database
  3. Connects Python modules
  4. 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.

Q2
πŸ–±οΈ Cursor Object

Which function is used to create a cursor object when interacting with an SQL database in Python?

  1. create_cursor()
  2. make_cursor()
  3. cursor()
  4. 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.

Q3
▢️ execute()

In Python, what is the purpose of the execute() method when working with an SQL database?

  1. Executes SQL queries
  2. Defines a new table
  3. Imports data into Python
  4. 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.

Q4
πŸ’Ύ commit()

How is data committed (permanently saved) to an SQL database using Python?

  1. commit()
  2. apply()
  3. save()
  4. 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.

Q5
1️⃣ fetchone()

Which method retrieves the next single row of a query result set in Python?

  1. fetchrow()
  2. fetchnext()
  3. fetchone()
  4. 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.

Q6
βž• INSERT Queries

How do you perform an INSERT query using a cursor in Python?

  1. insert_query()
  2. execute_insert()
  3. execute(“INSERT …”)
  4. 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).

Q7
πŸ“‹ fetchall()

What does the fetchall() method do in Python when working with an SQL database?

  1. Fetches the first row of the result set
  2. Fetches all the rows of the result set as a list of tuples
  3. Fetches the last row of the result set
  4. 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.

Q8
πŸ”’ rowcount

How can you check the number of rows affected by the last executed query in Python?

  1. cursor.rowcount (accessed as a property, WITHOUT parentheses)
  2. rowcount()
  3. get_rowcount()
  4. 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.)

Q9
1️⃣ fetchone()

What is the purpose of the fetchone() method in Python when working with an SQL database?

  1. Fetches ALL rows of the result set at once
  2. Fetches only the LAST row of the result set
  3. Fetches the NEXT unread row of the result set (only the first row if called immediately after execute())
  4. 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.)

Q10
✏️ UPDATE Queries

How do you perform an UPDATE query using a cursor in Python?

  1. cursor_update()
  2. execute(“UPDATE …”)
  3. update_record()
  4. 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.

Q11
πŸ›‘οΈ Parameterized Queries

What is the purpose of using the %s format specifier when writing SQL queries in Python (with mysql.connector)?

  1. It’s purely decorative and has no functional effect
  2. It acts as a placeholder for values, letting you safely pass parameters into a query and helping prevent SQL injection
  3. It only works with numeric data types
  4. 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.

Q12
πŸ›‘οΈ Parameterized Queries

Besides using %s placeholders, what is another common way to build a query string with values in Python?

  1. Using the format() method or f-strings to insert values directly into the query text
  2. Only %s placeholders exist; there is no alternative
  3. Using the print() function
  4. 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.

Q13
πŸ”’ Closing Connections

Why is it important to close both the cursor and the connection after finishing database operations in Python?

  1. It’s not actually necessary; Python handles this entirely automatically with no downside to skipping it
  2. To release database resources and connections properly, preventing resource leaks
  3. To permanently delete all data in the database
  4. 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.

Q14
🧯 Error Handling

What is a recommended practice when performing database operations that might fail, such as a connection error or a bad query?

  1. Ignore all errors completely and let the entire program crash
  2. Wrap the database operations in a try-except block to handle potential errors gracefully
  3. Never use commit(), so errors can’t occur
  4. 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.

Q15
πŸ”— Connecting to SQL

Which of the following parameters are typically required when calling connect() to link Python with a MySQL database?

  1. Only the database name
  2. host, user, password, and database (or similar connection details)
  3. Only a username and a query string
  4. 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.

Q16
⭐ 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.")
  1. It only prepares the query text but never actually inserts anything into the database
  2. It inserts one new row (1, ‘Riya’, 85) into the Students table, permanently saves it, and reports 1 record inserted
  3. It raises an error, since %s cannot be used for text values like ‘Riya’
  4. 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.

Q17
⭐ 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)
  1. Only the first row is printed, then the loop stops
  2. All three rows are printed, one tuple per line, in the order they were retrieved
  3. Nothing is printed, since fetchall() cannot be used with a for loop
  4. 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.

Q18
πŸ’Ύ commit()

What happens if you execute an INSERT or UPDATE query but FORGET to call commit() afterward?

  1. The change is guaranteed to be saved permanently regardless
  2. 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)
  3. Python raises an immediate SyntaxError
  4. 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.

Q19
βš–οΈ fetchone() and fetchall()

What is the key difference between fetchone() and fetchall() when reading query results?

  1. They are functionally identical in every way
  2. fetchone() returns just the next single row (or None); fetchall() returns every remaining row at once, as a list of tuples
  3. fetchall() can only be used with SELECT * queries
  4. 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.

Q20
πŸ—‘οΈ DELETE Queries

How do you perform a DELETE query using a cursor in Python?

  1. delete_record()
  2. cursor.remove()
  3. execute(“DELETE FROM table WHERE condition”)
  4. 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.

Jitendra Singh
βœ” Verified Educator

Jitendra Singh

Founder of CBSEPython.in

I help CBSE Class 9–12 students learn Python, Information Technology, Artificial Intelligence and Computer Science through easy notes, quizzes, MCQs and sample papers.

Read More About Me β†’