Playing as a guest? to earn XP and track your progress.
๐ Interface Python with MySQL Quiz
๐ Interface Python with MySQL
Which Python module is used to connect Python with a MySQL database?
import sqlite3
import mysql.connector
import database
import sql
mysql.connector (or pymysql) is the module used to establish a connection between Python and MySQL. It must be imported before any database operations can be performed.
Which command is used to install the MySQL connector module for Python?
install mysql-connector-python
pip install mysql-connector-python
python install mysql.connector
apt-get mysql.connector
pip is Python's package installer. The correct command is: pip install mysql-connector-python. This is run once in the terminal/command prompt before writing any Python-MySQL code.
Which function is used to create a connection object between Python and MySQL?
mysql.connector.open()
mysql.connector.link()
mysql.connector.connect()
mysql.connector.start()
mysql.connector.connect() creates and returns a connection object. It accepts parameters like host, user, password, and database to establish the connection.
Which of the following is the correct way to create a connection to a MySQL database?
conn = mysql.connector.connect('localhost', 'root', 'pass', 'SchoolDB')
conn = mysql.connector.connect(host='localhost', user='root', password='pass', database='SchoolDB')
conn = mysql.connect(host='localhost', user='root', password='pass', db='SchoolDB')
conn = connector.mysql(host='localhost', user='root', password='pass')
The correct syntax uses keyword arguments: host, user, password, and database. Positional arguments are not supported and 'db' is not the correct parameter name in mysql.connector.
What does the host parameter represent in mysql.connector.connect()?
The name of the database to connect to
The MySQL username
The address of the MySQL server
The port number for the connection
The host parameter specifies the address of the MySQL server. For a local machine it is 'localhost' or '127.0.0.1'. For a remote server it would be the server's IP address or domain name.
What is the correct order of the 5 steps for Python-MySQL connectivity?
Import โ Execute โ Connect โ Cursor โ Fetch & Close
Connect โ Import โ Cursor โ Execute โ Fetch & Close
Import โ Connect โ Cursor โ Execute โ Fetch & Close
Import โ Cursor โ Connect โ Execute โ Fetch & Close
The mandatory order is: (1) Import the connector module, (2) Create a Connection, (3) Create a Cursor object, (4) Execute SQL queries, (5) Fetch results and Close the connection.
What is a cursor object in Python-MySQL connectivity?
A pointer that moves through the result set one row at a time in the display
An object used to send SQL queries to MySQL and receive results
A backup copy of the database connection
The MySQL server's response object
A cursor object is the tool (like a 'pen') that sends SQL statements to the MySQL server and receives the results back into Python. It is created from the connection object using conn.cursor().
How is a cursor object created from a connection object conn?
cursor = conn.create_cursor()
cursor = conn.get_cursor()
cursor = conn.cursor()
cursor = mysql.cursor(conn)
The cursor is created by calling the cursor() method on the connection object: cursor = conn.cursor(). This creates a new cursor associated with the current connection.
Which method is used to send and execute an SQL query to the MySQL server?
cursor.run()
cursor.query()
cursor.send()
cursor.execute()
cursor.execute(query) sends the SQL query string to the MySQL server for execution. For parameterised queries, values are passed as the second argument: cursor.execute(query, values).
Which method retrieves ALL rows from the result of a SELECT query at once?
cursor.getall()
cursor.fetchall()
cursor.readall()
cursor.selectall()
cursor.fetchall() retrieves all remaining rows from the result set and returns them as a list of tuples. Each tuple represents one row from the database.
What does cursor.fetchone() return when there are no more rows to fetch?
An empty list []
An empty tuple ()
None
It raises an error
cursor.fetchone() returns None when there are no more rows to retrieve. This is commonly used as a loop condition: while row is not None: ... to process all rows one at a time.
What data type does cursor.fetchall() return?
A single tuple
A string
A list of tuples
A dictionary
cursor.fetchall() returns a list of tuples. Each tuple in the list represents one row from the database. Individual values are accessed by index: row[0], row[1], etc.
Which method fetches only the next n rows from the result set?
cursor.fetch(n)
cursor.fetchmany(n)
cursor.getnext(n)
cursor.limit(n)
cursor.fetchmany(n) retrieves the next n rows from the result set as a list of tuples. It is useful when you want to process data in batches rather than all at once.
After executing cursor.execute('SELECT * FROM Employee'), what does cursor.fetchone() return for the first call?
All rows as a list
The first row as a tuple
The column names
The number of rows
The first call to cursor.fetchone() returns the first row from the result set as a tuple. Each subsequent call returns the next row. When no rows remain, it returns None.
Which method checks whether the connection to MySQL is still active?
conn.active()
conn.is_connected()
conn.check()
conn.status()
conn.is_connected() returns True if the connection to the MySQL server is currently active, and False otherwise. It is commonly used to verify a successful connection before executing queries.
What does cursor.rowcount return after a SELECT query?
The number of columns in the result
Always returns -1 for SELECT queries
The number of rows fetched or affected
The total number of rows in the table
cursor.rowcount returns the number of rows that were affected by the last DML operation (INSERT/UPDATE/DELETE) or the number of rows retrieved by the last SELECT. It is useful to confirm how many rows were processed.
What is the correct way to close a cursor and connection after use?
conn.close() followed by cursor.close()
cursor.close() followed by conn.close()
Just conn.close() โ cursor closes automatically
mysql.connector.close(conn, cursor)
Best practice is to close the cursor first, then the connection: cursor.close() then conn.close(). Closing the cursor releases its resources while keeping the connection available; closing the connection then terminates the session.
Why is it important to close the database connection after use?
It deletes the data from the database
MySQL requires connections to be closed before it can process queries
Unclosed connections waste server resources and can prevent new connections
Python will throw an error if the connection is not closed
MySQL has a limit on simultaneous connections. Unclosed connections hold server resources even after the program ends. Accumulating unclosed connections can exhaust the connection pool and prevent new users from connecting.
What is a Parameterised Query in Python-MySQL?
A query that uses column names as parameters
A query where values use %s placeholders and are passed separately as a tuple
A query stored permanently in the database
A query that runs with administrator parameters
A parameterised query uses %s as a placeholder in the SQL string for values, and passes the actual values separately as a tuple to cursor.execute(). This keeps the SQL structure and data separate.
What symbol is used as a placeholder for values in parameterised queries with mysql.connector?
? (question mark)
(hash)
@ (at sign)
%s
mysql.connector uses %s as the placeholder for values in parameterised queries. Note: sqlite3 uses ? as its placeholder, but mysql.connector specifically uses %s.
Which of the following correctly executes a parameterised query to find employees in the 'IT' department?
cursor.execute('SELECT * FROM Employee WHERE Dept = IT')
cursor.execute('SELECT * FROM Employee WHERE Dept = %s', 'IT')
cursor.execute('SELECT * FROM Employee WHERE Dept = %s', ('IT',))
cursor.execute('SELECT * FROM Employee WHERE Dept = ?', ('IT',))
The value must be passed as a tuple: ('IT',) โ note the trailing comma for a single-value tuple. Passing just 'IT' as a string (not a tuple) will cause an error. mysql.connector uses %s not ?.
A student writes cursor.execute(query, ('IT')) instead of cursor.execute(query, ('IT',)). What is the problem?
There is no problem โ both work the same way
('IT') is treated as just the string 'IT' in parentheses, not a tuple
The query will run but return no results
MySQL does not accept strings in execute()
In Python, ('IT') without a trailing comma is NOT a tuple โ it is simply the string 'IT' surrounded by parentheses. A single-element tuple REQUIRES a trailing comma: ('IT',). Without it, cursor.execute() receives a string instead of a tuple and raises a TypeError.
What security attack does a parameterised query prevent?
Brute Force Attack
SQL Injection Attack
DDoS Attack
Man-in-the-Middle Attack
Parameterised queries prevent SQL Injection attacks, where malicious user input contains SQL commands that manipulate the query structure. By treating values as data (not SQL), parameterised queries neutralise this threat.
A user enters IT' OR '1'='1 as input for department. Which code is VULNERABLE to SQL Injection?
cursor.execute('SELECT * FROM Employee WHERE Dept = %s', (dept,))
cursor.execute('SELECT * FROM Employee WHERE Dept = ' + dept)
cursor.execute('SELECT * FROM Employee WHERE Dept = %s', (dept,))
Both A and C
String concatenation (+ dept) directly embeds user input into SQL, allowing SQL Injection. The malicious input becomes: WHERE Dept = 'IT' OR '1'='1' โ which returns ALL rows. Parameterised queries (%s with tuple) treat the input as a literal string, preventing injection.
Which method is used to PERMANENTLY save INSERT, UPDATE, or DELETE changes to the MySQL database?
cursor.save()
conn.commit()
cursor.execute()
conn.push()
conn.commit() permanently writes all pending DML changes to the database. Without calling commit(), the changes exist only in the current session and are lost when the connection closes.
What happens if you execute an INSERT statement but forget to call conn.commit()?
The record is saved permanently as usual
Python automatically commits after every execute()
The changes are lost when the connection closes and not saved to the database
MySQL throws an error immediately
Without conn.commit(), DML changes are stored in a temporary transaction buffer. When the connection closes, uncommitted changes are automatically rolled back โ the data is never permanently saved to the database.
Which method cancels all uncommitted changes and restores the database to its previous state?
conn.undo()
conn.revert()
conn.rollback()
conn.cancel()
conn.rollback() cancels all uncommitted DML changes (INSERT, UPDATE, DELETE) and restores the database to the state it was in after the last commit(). It is typically called in the except block of a try-except-finally structure.
What is the correct syntax to insert a new employee record using a parameterised query?
cursor.execute('INSERT INTO Employee VALUES %s', (101, 'Priya', 'Sales', 45000, 'Delhi'))
cursor.execute('INSERT INTO Employee VALUES (%s, %s, %s, %s, %s)', (101, 'Priya', 'Sales', 45000, 'Delhi'))
cursor.execute('INSERT INTO Employee VALUES (101, Priya, Sales, 45000, Delhi)')
cursor.insert('Employee', (101, 'Priya', 'Sales', 45000, 'Delhi'))
Each value in the INSERT must have its own %s placeholder. The values tuple must have the same number of elements as there are %s placeholders. The tuple is passed as the second argument to cursor.execute().
After inserting a record with cursor.execute() and conn.commit(), what does cursor.rowcount return?
0
1
The new record's ID
Total number of rows in the table
After a successful INSERT of one record, cursor.rowcount returns 1 โ indicating that 1 row was affected. For bulk inserts using executemany(), it returns the total number of rows inserted.
Which method inserts multiple rows into a table efficiently with a single SQL template?
cursor.execute_bulk()
cursor.insertmany()
cursor.executemany()
cursor.executeall()
cursor.executemany(query, list_of_tuples) executes the same SQL query multiple times, once for each tuple in the list. It is far more efficient than calling cursor.execute() in a loop for each row.
What does cursor.executemany() accept as its second argument?
A single tuple of values
A string of comma-separated values
A list of tuples, one tuple per row
A dictionary of column-value pairs
cursor.executemany(query, data) accepts a list of tuples as its second argument. Each tuple contains the values for one row. The query is executed once for each tuple in the list.
Which of the following correctly inserts 3 employee records using executemany()?
cursor.executemany('INSERT INTO Employee VALUES (%s,%s)', [(101,'Priya'), (102,'Arjun'), (103,'Sita')])
cursor.executemany('INSERT INTO Employee VALUES %s', (101,'Priya',102,'Arjun'))
cursor.execute_bulk('INSERT INTO Employee VALUES (%s)', [(101,), (102,), (103,)])
cursor.executemany('INSERT INTO Employee VALUES (%s)', 101, 102, 103)
executemany() takes the SQL template as the first argument and a list of tuples as the second. Each tuple matches the %s placeholders in the query. The number of %s must match the number of elements in each tuple.
Which of the following correctly updates the salary of the employee with EmpId=101 using a parameterised query?
cursor.execute('UPDATE Employee Salary=50000 WHERE EmpId=101')
cursor.execute('UPDATE Employee SET Salary=%s WHERE EmpId=%s', (50000, 101))
cursor.execute('UPDATE Employee SET Salary=%s WHERE EmpId=%s', (101, 50000))
cursor.update('Employee', Salary=50000, EmpId=101)
The tuple values must match the %s placeholders in order. SET Salary=%s โ first value is 50000. WHERE EmpId=%s โ second value is 101. So the tuple is (50000, 101). Option C has the values reversed.
What is the difference between cursor.execute() and cursor.executemany()?
execute() runs SELECT; executemany() runs INSERT only
execute() runs one query once; executemany() runs one query multiple times with different values
executemany() is faster for SELECT; execute() is faster for INSERT
There is no practical difference between the two
cursor.execute() runs a single SQL statement with one set of values. cursor.executemany() runs the same SQL statement repeatedly, once for each set of values in the provided list. It is more efficient for bulk operations.
In which Python block should conn.close() ideally be placed to ensure the connection is always closed?
try block
except block
finally block
else block
The finally block always executes regardless of whether an exception occurred or not. Placing conn.close() in finally guarantees the connection is always closed โ whether the code succeeded or raised an error.
What is the purpose of conn.autocommit = True?
Automatically creates a backup before each query
Makes every DML statement immediately and permanently saved without needing conn.commit()
Automatically reconnects if the connection drops
Automatically fetches all results after execute()
When conn.autocommit = True, every DML statement (INSERT/UPDATE/DELETE) is immediately committed after execution without needing an explicit conn.commit() call. The downside is that conn.rollback() cannot undo changes since they are committed instantly.
Which of the following code snippets has an error?
cursor.execute('SELECT * FROM Employee WHERE Dept = %s', ('IT',))
cursor.execute('SELECT * FROM Employee WHERE Dept = %s AND City = %s', ('IT', 'Delhi'))
cursor.execute('SELECT * FROM Employee WHERE Salary > %s', (50000,))
cursor.execute('SELECT * FROM Employee WHERE Dept = %s', 'IT')
Option D passes 'IT' as a plain string, not a tuple. cursor.execute() expects the values to be passed as a tuple (or list). The correct form is ('IT',) with the trailing comma to make it a tuple.
What does each element in the list returned by cursor.fetchall() represent?
A column name from the table
A single cell value from the table
One row from the database table as a tuple
The SQL query that was executed
cursor.fetchall() returns a list of tuples. Each tuple in the list represents one complete row from the database. Individual column values are accessed by index: row[0] for the first column, row[1] for the second, etc.
Identify the error in the following Python code:
import mysql.connector
conn = mysql.connector.connect(host='localhost', user='root', password='pass', database='SchoolDB')
cursor = conn.cursor()
cursor.execute('INSERT INTO Student VALUES (1, "Priya", 91)')
print('Inserted!')
cursor.close()
conn.close()The import statement is wrong
cursor() should be conn.cursor()
conn.commit() is missing after execute()
fetchall() must be called after INSERT
conn.commit() is missing. After executing an INSERT statement, conn.commit() must be called to permanently save the data to the database. Without it, the INSERT is rolled back when the connection closes and no data is actually saved.
A Python program connects to MySQL and runs: cursor.execute('SELECT * FROM Employee WHERE City = %s', ('Delhi',)). The Employee table has 3 Delhi employees. What does cursor.rowcount return?
0
3
6 (total rows in table)
-1
cursor.rowcount returns 3 โ the number of rows that matched the SELECT query condition. It reflects how many rows are in the result set, which is 3 Delhi employees.
Which statement about conn.rollback() is TRUE?
It undoes all changes including those already committed
It undoes only uncommitted DML changes since the last commit()
It deletes all rows from the table
It is the same as conn.close()
conn.rollback() only undoes changes that have NOT yet been committed. It restores the database to the state it was in after the last conn.commit() call. Already-committed changes cannot be rolled back.
Which of the following is the correct way to display rows fetched by cursor.fetchall() if the Employee table has columns EmpId, Name, Dept, Salary, City?
for row in cursor.fetchall(): print(row.Name)
for row in cursor: print(row[1])
records = cursor.fetchall() for row in records: print(row[1])
print(cursor.fetchall().Name)
fetchall() returns a list of tuples. Rows are accessed by index โ row[0] is EmpId, row[1] is Name, etc. You cannot use attribute-style access like row.Name. The result must be stored first, then iterated.
What is the output of the following code if Employee table has 4 rows?
cursor.execute('SELECT * FROM Employee')
print(cursor.fetchone())
print(cursor.fetchone())Prints all 4 rows twice
Prints the first row twice
Prints the first row, then the second row
Prints None, None
Each call to fetchone() returns the NEXT row in sequence. The first call returns row 1 (as a tuple); the second call returns row 2 (the next one). The cursor advances with each call โ it does NOT restart.
Which of the following Python programs correctly fetches and prints all employees using fetchone() in a loop?
row = cursor.fetchone() for row in cursor: print(row)
while cursor.fetchone() != None: print(cursor.fetchone())
row = cursor.fetchone() while row is not None: print(row) row = cursor.fetchone()
for i in range(cursor.rowcount): print(cursor.fetchone())
The correct pattern is: fetch the first row before the loop, check if it's None in the while condition, print it, then fetch the next row at the end of the loop body. Option B skips every other row (fetches inside condition AND inside body).
A student wants to search for employees by salary using user input. Which code correctly uses a parameterised query?
sal = int(input('Enter salary: ')) cursor.execute('SELECT * FROM Employee WHERE Salary > ' + sal)
sal = int(input('Enter salary: ')) cursor.execute('SELECT * FROM Employee WHERE Salary > %s', sal)
sal = int(input('Enter salary: ')) cursor.execute('SELECT * FROM Employee WHERE Salary > %s', (sal,))
sal = int(input('Enter salary: ')) cursor.execute(f'SELECT * FROM Employee WHERE Salary > {sal}')
Option C correctly uses a parameterised query with %s placeholder and passes the value as a single-element tuple (sal,). Option A uses string concatenation with an int (type error). Option B passes sal as a plain value, not a tuple. Option D uses f-string which is also vulnerable to injection.
Which of the following is NOT a valid fetch method in mysql.connector?
cursor.fetchone()
cursor.fetchall()
cursor.fetchmany(5)
cursor.fetchnext()
cursor.fetchnext() does not exist in mysql.connector. The three valid fetch methods are: fetchone() (one row), fetchall() (all rows), and fetchmany(n) (next n rows).
After calling cursor.fetchall(), what does calling cursor.fetchone() return?
The first row again
None โ because fetchall() already consumed all rows
The last row
An error is raised
cursor.fetchall() consumes ALL rows from the result set. After fetchall() is called, the cursor's position is at the end โ there are no more rows to fetch. A subsequent fetchone() returns None.
What does conn.autocommit = False (the default setting) mean?
Every query is automatically rolled back after execution
DML changes are NOT automatically saved โ you must call conn.commit() explicitly
SELECT queries will not return any results
The connection cannot be closed without a commit
autocommit = False (the default) means changes from INSERT/UPDATE/DELETE are held in a transaction and NOT permanently saved until you explicitly call conn.commit(). This allows you to use rollback() if something goes wrong.
Which error would the following code produce?
import mysql.connector
conn = mysql.connector.connect(host='localhost', user='root', password='wrong_pass', database='SchoolDB')
cursor = conn.cursor()SyntaxError
mysql.connector.errors.ProgrammingError
mysql.connector.errors.DatabaseError or Access Denied error
AttributeError
Providing a wrong password causes MySQL to reject the connection with an 'Access Denied' error. mysql.connector raises this as a DatabaseError or InterfaceError. This is why try-except blocks are important in database connectivity code.
Which of the following complete programs correctly connects to MySQL, fetches all IT employees, and properly closes the connection?
import mysql.connector conn = mysql.connect(host='localhost',user='root',password='pass',database='DB') cursor = conn.cursor() cursor.execute('SELECT * FROM Employee WHERE Dept=IT') print(cursor.fetchall())
import mysql.connector conn = mysql.connector.connect(host='localhost',user='root',password='pass',database='DB') cursor = conn.cursor() cursor.execute('SELECT * FROM Employee WHERE Dept=%s',('IT',)) rows = cursor.fetchall() for row in rows: print(row) cursor.close() conn.close()
import mysql.connector conn = mysql.connector.connect(host='localhost',user='root',password='pass',database='DB') cursor = conn.cursor() cursor.execute('SELECT * FROM Employee WHERE Dept=%s','IT') print(cursor.fetchall()) conn.close()
import mysql conn = mysql.connect(host='localhost',user='root',password='pass',database='DB') cursor = conn.cursor() cursor.run('SELECT * FROM Employee WHERE Dept=IT') print(cursor.fetchall())
Option B is the only correct one: uses mysql.connector.connect() (not mysql.connect()), passes 'IT' correctly as a tuple ('IT',), uses cursor.execute() (not run()), fetches with fetchall(), iterates over rows, and properly closes both cursor and connection.
What is the purpose of using try-except-finally in Python-MySQL programs?
To make the program run faster
To handle connection errors gracefully and ensure the connection is always closed
To automatically commit all changes
To retry failed queries automatically
try-except-finally ensures: the try block attempts the database operations, the except block handles any errors (like wrong password or network issues), and the finally block ALWAYS runs to close the connection โ even if an error occurred.
How many %s placeholders are needed in this query?
'INSERT INTO Student (RollNo, Name, Class, Marks) VALUES (%s, %s, %s, %s)'
And how many values must be in the corresponding tuple?
3 placeholders, 3 values
4 placeholders, 4 values
4 placeholders, any number of values
1 placeholder for all values
There are 4 columns (RollNo, Name, Class, Marks) so 4 %s placeholders are needed. The values tuple must also have exactly 4 elements โ one for each placeholder, in the same order as the columns.
Which of the following statements about cursor.fetchmany(3) is TRUE?
It always returns exactly 3 rows regardless of how many rows exist
It returns up to 3 rows; fewer if less than 3 rows remain
It returns 3 columns of the result
It skips 3 rows and returns the rest
cursor.fetchmany(n) returns UP TO n rows. If fewer than n rows remain in the result set, it returns only those remaining rows. If no rows remain, it returns an empty list.
A program inserts 5 records using cursor.executemany(). What does cursor.rowcount return after conn.commit()?
1
0
5
-1
After cursor.executemany() inserts 5 rows, cursor.rowcount returns 5 โ reflecting the total number of rows that were affected by the executemany() operation.
Which is the correct import statement to also catch MySQL-specific errors in a try-except block?
from mysql.connector import Error
import mysql.Error
from mysql import connector.Error
import mysql_error
The correct import is: from mysql.connector import Error. This allows you to write except Error as e: to catch MySQL-specific exceptions like connection errors, syntax errors, and constraint violations.