Exit Chapter 13 ยท ๐Ÿ”— Interface Python with MySQL โ€” Quiz

Playing as a guest? to earn XP and track your progress.

Question 1 of 55 0 correct so far

๐Ÿ”— Interface Python with MySQL Quiz

Q1.

Which Python module is used to connect Python with a MySQL database?

Explanation

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.

Q2.

Which command is used to install the MySQL connector module for Python?

Explanation

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.

Q3.

Which function is used to create a connection object between Python and MySQL?

Explanation

mysql.connector.connect() creates and returns a connection object. It accepts parameters like host, user, password, and database to establish the connection.

Q4.

Which of the following is the correct way to create a connection to a MySQL database?

Explanation

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.

Q5.

What does the host parameter represent in mysql.connector.connect()?

Explanation

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.

Q6.

What is the correct order of the 5 steps for Python-MySQL connectivity?

Explanation

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.

Q7.

What is a cursor object in Python-MySQL connectivity?

Explanation

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().

Q8.

How is a cursor object created from a connection object conn?

Explanation

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.

Q9.

Which method is used to send and execute an SQL query to the MySQL server?

Explanation

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).

Q10.

Which method retrieves ALL rows from the result of a SELECT query at once?

Explanation

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.

Q11.

What does cursor.fetchone() return when there are no more rows to fetch?

Explanation

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.

Q12.

What data type does cursor.fetchall() return?

Explanation

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.

Q13.

Which method fetches only the next n rows from the result set?

Explanation

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.

Q14.

After executing cursor.execute('SELECT * FROM Employee'), what does cursor.fetchone() return for the first call?

Explanation

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.

Q15.

Which method checks whether the connection to MySQL is still active?

Explanation

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.

Q16.

What does cursor.rowcount return after a SELECT query?

Explanation

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.

Q17.

What is the correct way to close a cursor and connection after use?

Explanation

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.

Q18.

Why is it important to close the database connection after use?

Explanation

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.

Q19.

What is a Parameterised Query in Python-MySQL?

Explanation

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.

Q20.

What symbol is used as a placeholder for values in parameterised queries with mysql.connector?

Explanation

mysql.connector uses %s as the placeholder for values in parameterised queries. Note: sqlite3 uses ? as its placeholder, but mysql.connector specifically uses %s.

Q21.

Which of the following correctly executes a parameterised query to find employees in the 'IT' department?

Explanation

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 ?.

Q22.

A student writes cursor.execute(query, ('IT')) instead of cursor.execute(query, ('IT',)). What is the problem?

Explanation

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.

Q23.

What security attack does a parameterised query prevent?

Explanation

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.

Q24.

A user enters IT' OR '1'='1 as input for department. Which code is VULNERABLE to SQL Injection?

Explanation

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.

Q25.

Which method is used to PERMANENTLY save INSERT, UPDATE, or DELETE changes to the MySQL database?

Explanation

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.

Q26.

What happens if you execute an INSERT statement but forget to call conn.commit()?

Explanation

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.

Q27.

Which method cancels all uncommitted changes and restores the database to its previous state?

Explanation

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.

Q28.

What is the correct syntax to insert a new employee record using a parameterised query?

Explanation

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().

Q29.

After inserting a record with cursor.execute() and conn.commit(), what does cursor.rowcount return?

Explanation

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.

Q30.

Which method inserts multiple rows into a table efficiently with a single SQL template?

Explanation

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.

Q31.

What does cursor.executemany() accept as its second argument?

Explanation

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.

Q32.

Which of the following correctly inserts 3 employee records using executemany()?

Explanation

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.

Q33.

Which of the following correctly updates the salary of the employee with EmpId=101 using a parameterised query?

Explanation

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.

Q34.

What is the difference between cursor.execute() and cursor.executemany()?

Explanation

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.

Q35.

In which Python block should conn.close() ideally be placed to ensure the connection is always closed?

Explanation

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.

Q36.

What is the purpose of conn.autocommit = True?

Explanation

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.

Q37.

Which of the following code snippets has an error?

Explanation

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.

Q38.

What does each element in the list returned by cursor.fetchall() represent?

Explanation

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.

Q39.

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()
Explanation

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.

Q40.

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?

Explanation

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.

Q41.

Which statement about conn.rollback() is TRUE?

Explanation

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.

Q42.

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?

Explanation

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.

Q43.

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())
Explanation

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.

Q44.

Which of the following Python programs correctly fetches and prints all employees using fetchone() in a loop?

Explanation

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).

Q45.

A student wants to search for employees by salary using user input. Which code correctly uses a parameterised query?

Explanation

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.

Q46.

Which of the following is NOT a valid fetch method in mysql.connector?

Explanation

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).

Q47.

After calling cursor.fetchall(), what does calling cursor.fetchone() return?

Explanation

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.

Q48.

What does conn.autocommit = False (the default setting) mean?

Explanation

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.

Q49.

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()
Explanation

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.

Q50.

Which of the following complete programs correctly connects to MySQL, fetches all IT employees, and properly closes the connection?

Explanation

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.

Q51.

What is the purpose of using try-except-finally in Python-MySQL programs?

Explanation

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.

Q52.

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?

Explanation

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.

Q53.

Which of the following statements about cursor.fetchmany(3) is TRUE?

Explanation

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.

Q54.

A program inserts 5 records using cursor.executemany(). What does cursor.rowcount return after conn.commit()?

Explanation

After cursor.executemany() inserts 5 rows, cursor.rowcount returns 5 โ€” reflecting the total number of rows that were affected by the executemany() operation.

Q55.

Which is the correct import statement to also catch MySQL-specific errors in a try-except block?

Explanation

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.