Circle of Learning Logo CIRCLE OF LEARNING Excellence in Education
CBSE Class 12 · Computer Science Chapter 11 Session 2026-27

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
con=connect(host,user,password,database)\text{con} = \text{connect}(\text{host}, \text{user}, \text{password}, \text{database})

Returns a MySQLConnection object; raises Error if credentials or server are invalid.

2 Cursor Object Creation
cursor=con.cursor()\text{cursor} = \text{con.cursor}()

Creates working cursor to execute SQL commands and traverse query result sets.

3 Parameterized Query (SQL Injection Prevention)
execute(Qparam,tuple of values)\text{execute}(Q_{\text{param}}, \text{tuple of values})

Uses %s placeholders; driver safely escapes and formats variables.

4 Fetching All Records
fetchall()  ⟹  [(row1),(row2),…,(rown)]\text{fetchall}() \implies [(\text{row}_1), (\text{row}_2), \dots, (\text{row}_n)]

Loads entire result set into Python list; returns empty list if no rows.

5 Fetching Single Next Record
fetchone()  ⟹  (tuple)∨None\text{fetchone}() \implies (\text{tuple}) \lor \text{None}

Conserves memory by iterating one record at a time in a while loop.

6 Fetching Fixed Batch of Records
fetchmany(k)  ⟹  [tuple1,…,tuplek]\text{fetchmany}(k) \implies [\text{tuple}_1, \dots, \text{tuple}_k]

Optimal for paginated result display.

7 Transaction Commit Requirement for DML
DML+con.commit()  ⟹  Persistent on Disk\text{DML} + \text{con.commit}() \implies \text{Persistent on Disk}

Without commit(), modifications are discarded when connection closes.

8 Affected Row Count Property
rows_affected=cur.rowcount\text{rows\_affected} = \text{cur.rowcount}

Returns integer count of rows updated, deleted, or inserted.

9 Connection Verification Helper
con.is_connected()∈{True,False}\text{con.is\_connected}() \in \{\text{True}, \text{False}\}

Tests whether socket connection to database server is alive.

10 Resource Clean-Up Closing Protocol
cur.close()→con.close()\text{cur.close}() \to \text{con.close}()

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.

Ans: ```python import mysql.connector try: con = mysql.connector.connect( host="localhost", user="root", password="tiger", database="COMPANY" ) if con.is_connected(): cur = con.cursor() query = "SELECT * FROM EMPLOYEE WHERE SALARY > 50000" cur.execute(query) records = cur.fetchall() print(f"Total Employees found: {len(records)}") for row in records: print(row) cur.close() con.close() except mysql.connector.Error as err: print(f"Database Error: {err}") ```

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.

Ans: ```python import mysql.connector def insert_student(roll, name, marks): try: con = mysql.connector.connect( host="localhost", user="root", password="admin", database="SCHOOL" ) cur = con.cursor() sql = "INSERT INTO STUDENT (RollNo, Name, Marks) VALUES (%s, %s, %s)" cur.execute(sql, (roll, name, marks)) con.commit() print(f"{cur.rowcount} record inserted successfully.") cur.close() con.close() except mysql.connector.Error as e: print(f"Failed to insert record: {e}") ```

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.

← View All 11 Chapters in Class 12 Computer Science Formula Book