Python - MySQL Database Connectivity Formulas & Cheat Sheet
Complete chapter-wise reference, step-by-step formula explanations, structured table, and board exam trap warnings.
Core Concepts & Theoretical Foundations
- Database Connectivity: Interfacing Python backend scripts with MySQL relational database using `mysql.connector` driver module.
- Connection Workflow: 1) Import driver (`import mysql.connector`), 2) Establish connection object (`con = mysql.connector.connect(host, user, password, database)`), 3) Create cursor object (`cur = con.cursor()`), 4) Execute SQL query (`cur.execute(query)`), 5) Fetch result rows (`fetchone()`, `fetchall()`, `fetchmany(n)`), 6) Commit transaction for DML changes (`con.commit()`), 7) Close cursor and connection (`cur.close()`, `con.close()`).
- Fetching Methods: `cur.fetchone()` returns single tuple or `None`; `cur.fetchall()` returns list of all tuples; `cur.fetchmany(n)` returns list of next n tuples.
- Transaction Commit & Rollback: DML statements (INSERT, UPDATE, DELETE) modify the database buffer; changes are made permanent ONLY when `con.commit()` is called. `con.rollback()` undoes uncommitted changes.
Chapter Formulas & Equations (10 entries)
| # | Topic / Formula Name | Mathematical Form & Equation | Conditions, Meaning & Board Tips |
|---|---|---|---|
| 1 | MySQL Connection Establishment Formula |
|
Returns a MySQLConnection object; raises Error if credentials or server are invalid. |
| 2 | Cursor Object Creation |
|
Creates working cursor to execute SQL commands and traverse query result sets. |
| 3 | Parameterized Query (SQL Injection Prevention) |
|
Uses %s placeholders; driver safely escapes and formats variables. |
| 4 | Fetching All Records |
|
Loads entire result set into Python list; returns empty list if no rows. |
| 5 | Fetching Single Next Record |
|
Conserves memory by iterating one record at a time in a while loop. |
| 6 | Fetching Fixed Batch of Records |
|
Optimal for paginated result display. |
| 7 | Transaction Commit Requirement for DML |
|
Without commit(), modifications are discarded when connection closes. |
| 8 | Affected Row Count Property |
|
Returns integer count of rows updated, deleted, or inserted. |
| 9 | Connection Verification Helper |
|
Tests whether socket connection to database server is alive. |
| 10 | Resource Clean-Up Closing Protocol |
|
Frees database thread connections and memory handles. |
Step-by-Step Worked Board Exam Examples
Example 1: Write a complete Python script to connect to a MySQL database named `COMPANY` and display all employee records from table `EMPLOYEE` where `SALARY > 50000`.
1. Import `mysql.connector`.
2. Establish connection with host, user, password, and database `COMPANY`.
3. Create cursor object.
4. Execute query: `SELECT * FROM EMPLOYEE WHERE SALARY > 50000`.
5. Fetch all rows using `cur.fetchall()` and iterate through them printing each tuple.
6. Close cursor and connection inside a finally block.
Example 2: Write a Python function `insert_student(roll, name, marks)` to insert a new student record into table `STUDENT` in database `SCHOOL` using parameterized queries and commit the transaction.
1. Connect to MySQL database `SCHOOL`.
2. Prepare query string with placeholders: `INSERT INTO STUDENT (RollNo, Name, Marks) VALUES (%s, %s, %s)`.
3. Prepare data tuple: `data = (roll, name, marks)`.
4. Execute via `cur.execute(sql, data)`.
5. Call `con.commit()` to persist changes permanently.
6. Print success message and close connection.
Common Mistakes to Avoid in Exam
- Forgetting `con.commit()` after DML statements: Calling `cur.execute("INSERT...")` without `con.commit()` leaves changes in the buffer, so records vanish when the script finishes.
- Calling `con.commit()` on the cursor instead of connection: `commit()` is a method of the CONNECTION object (`con.commit()`), NOT the cursor (`cur.commit()` causes AttributeError).
- Constructing queries using string concatenation: Writing `"SELECT * WHERE name = '" + name + "'"` makes code vulnerable to SQL Injection attacks; always pass `%s` placeholders with parameter tuples.
- Calling `fetchall()` after non-SELECT statements: Calling `fetchall()` after INSERT or UPDATE raises `InterfaceError: No result set to fetch`.
Target Practice Questions
Q1. Which method is used to verify if a MySQL database connection is currently active?
Correct Answer: `con.is_connected()`
Q2. What happens if an error occurs during execution before `con.commit()`?
Correct Answer: The transaction can be rolled back using `con.rollback()`, ensuring the database remains in its previous consistent state.
Q3. What data type does `cur.fetchall()` return in Python?
Correct Answer: A list of tuples, where each tuple represents a single table row.
Frequently Asked Questions
Q. What is the purpose of the `cursor` object in Python database connectivity?
The `cursor` object acts as a middleware control structure that allows Python to execute SQL commands against the database and navigate through the resulting rows of a query.
Q. Why is `con.commit()` required for INSERT, UPDATE, and DELETE, but not for SELECT?
`SELECT` is a read-only query that does not modify database state. `INSERT`, `UPDATE`, and `DELETE` alter stored data, requiring explicit transaction commit to make changes permanent on physical storage.
Q. What does `cur.fetchone()` return when all records have been read?
It returns `None`.
Q. What is the difference between `cur.fetchall()` and `cur.fetchmany(n)`?
`cur.fetchall()` fetches all remaining rows of the query result as a list of tuples. `cur.fetchmany(n)` fetches only the next `n` rows as a list of tuples.
Q. What does `cur.rowcount` return?
`cur.rowcount` returns the number of rows affected by an INSERT, UPDATE, or DELETE query, or the number of rows read so far by a SELECT query.