---
title: "Python MySQL Connectivity Class 12: Programs and Errors"
description: "Python MySQL connectivity for Class 12 CS: the four steps, programs with output, fetchone and fetchall, %s or format(), error messages, 4-mark answers."
canonical: https://learn.modernagecoders.com/cbse-class-12-computer-science-python-mysql-connectivity
source: src/pages/cbse-class-12-computer-science-python-mysql-connectivity.html
---
> Python MySQL connectivity for Class 12 CS: the four steps, programs with output, fetchone and fetchall, %s or format(), error messages, 4-mark answers.

Start here

## Courses on both sides of the connection

Connectivity needs a little Python and a little SQL at the same moment. Pick the course for the side that is slowing you down.

[![Computer Science Class 11 and 12 course thumbnail](/images/ip-cs-class-11-12.webp)  Both sides / 083 Computer Science 11 and 12 Python, MySQL and the interface between them in board order, so this topic arrives after the two it depends on. Open the course →](/courses/cbse-icse-computer-science-class-11-12-python-java-complete-course)[![Python for Teens course thumbnail](/images/python-teens.webp)  Python side Python for Teens Functions, loops, tuples and error handling through projects. Choose it if unpacking a row or writing a function still feels slow. Open the course →](/courses/python-complete-masterclass-teens)[![MySQL for Teens course thumbnail](/images/mysql-teens.webp)  MySQL side MySQL for Teens Queries, joins and table design, then apps in which Python talks to the database. A good follow-on to this page. Open the course →](/courses/mysql-mastery-for-teens)

Ans. The short version

Python MySQL connectivity in Class 12 means sending SQL from a Python program with the mysql.connector module. There are four steps: connect to the server, create a cursor, execute the query, then commit a change or fetch the rows of a SELECT; finally close the connection. In the CBSE 2026-27 sample paper it is a 4-mark question, and the report file needs at least four such programs. Modern Age Coders teaches it live, personalised one to one at your timing, on your own computer. You can take a priority demo, a full class, before enrolling.

Part 1. The skeleton

## What are the steps of Python MySQL connectivity in Class 12?

Connect, make a cursor, execute, then commit or fetch. Learn which object each function belongs to, because the connection and the cursor do different jobs.

1. #### Connect

  `con = mysql.connector.connect(host=..., user=..., password=..., database=...)` opens a line to the server and returns a connection object.
2. #### Create a cursor

  `cur = con.cursor()` returns the object that carries queries out and brings rows back.
3. #### Execute

  `cur.execute(query, values)` sends one SQL statement. No semicolon is needed inside the string.
4. #### Commit or fetch

  After INSERT, UPDATE or DELETE: `con.commit()`. After SELECT: `cur.fetchall()` or `cur.fetchone()`.

Then `con.close()`. Before all of it comes `import mysql.connector`, which works once the package mysql-connector-python is installed and the MySQL server is running.

### Who owns which function?

| Function | Belongs to | What it gives back |
| --- | --- | --- |
| `connect()` | mysql.connector | A connection object |
| `cursor()` | connection | A cursor object |
| `execute()` | cursor | Nothing you need; rows wait to be fetched |
| `fetchone()` | cursor | One row as a tuple, or None at the end |
| `fetchall()` | cursor | A list of the rows left, or [] if none |
| `rowcount` | cursor | A number. It is an attribute: no brackets |
| `commit()` | connection | Nothing; the change becomes permanent |
| `close()` | both | Nothing |

Writing `cur.commit()` stops the program: `'CMySQLCursor' object has no attribute 'commit'`. Remember it as: the **con**nection **co**mmits.

### Program 1. Create the database, the table and five rows

Our data is the log of a school sky club: what was seen, who saw it, how many stars they gave the view, and when. One rating is missing on purpose. This first program does not name a database in `connect()`, because it does not exist yet.

***Program 1**create and insert*

```
# Program 1: create the database and the table, then add five rows
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root",
                              password="your_password")
cur = con.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS skyclub")
cur.execute("USE skyclub")
cur.execute("DROP TABLE IF EXISTS sighting")
cur.execute("""CREATE TABLE sighting(
    sno     INT PRIMARY KEY,
    object  VARCHAR(20) NOT NULL,
    member  VARCHAR(20) NOT NULL,
    stars   INT,
    seen_on DATE)""")
rows = [(1, "Saturn", "Ira", 5, "2026-10-03"),
        (2, "Moon", "Dev", 4, "2026-10-03"),
        (3, "Pleiades", "Ira", 3, "2026-10-17"),
        (4, "Jupiter", "Zoya", 5, "2026-11-08"),
        (5, "Moon", "Ira", None, "2026-11-21")]
for row in rows:
    cur.execute("INSERT INTO sighting VALUES (%s, %s, %s, %s, %s)", row)
con.commit()
print("Rows added:", len(rows))
con.close()
```

Printed: **Rows added: 5**. Python's None is stored as NULL, and a date can be given as a string in the form YYYY-MM-DD. DROP TABLE lets you run it again while you practise; leave it out of real work.

**The password.** Every program here says `"your_password"`. Type your own in its place on your machine. In the exam, use the exact user, password, host and database given in the question.

Part 2. Reading rows

## fetchone and fetchall in Class 12: what each one returns

fetchone() returns the next row as a tuple, and fetchall() returns every row that has not been fetched yet as a list of tuples. A row is never handed over twice.

### Program 2. Display the table

***Program 2**display*

```
# Program 2: display every sighting
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root",
                              password="your_password",
                              database="skyclub")
cur = con.cursor()
cur.execute("SELECT * FROM sighting")
data = cur.fetchall()
for row in data:
    print(row)
print("Rows read:", cur.rowcount)
con.close()
```

***Output**MySQL*

```
(1, 'Saturn', 'Ira', 5, datetime.date(2026, 10, 3))
(2, 'Moon', 'Dev', 4, datetime.date(2026, 10, 3))
(3, 'Pleiades', 'Ira', 3, datetime.date(2026, 10, 17))
(4, 'Jupiter', 'Zoya', 5, datetime.date(2026, 11, 8))
(5, 'Moon', 'Ira', None, datetime.date(2026, 11, 21))
Rows read: 5
```

A DATE arrives as a Python date object and NULL arrives as None. Print `row[4]` by itself and you see 2026-10-03.

### One cursor, watched line by line

***Fetch test**five rows*

```
# fetchone, fetchall and rowcount on five rows
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root",
                              password="your_password",
                              database="skyclub")
cur = con.cursor()
cur.execute("SELECT sno, object FROM sighting ORDER BY sno")
print(cur.fetchone())
print(cur.rowcount)
print(cur.fetchone())
print(cur.fetchall())
print(cur.rowcount)
con.close()
```

***Output**MySQL*

```
(1, 'Saturn')
1
(2, 'Moon')
[(3, 'Pleiades'), (4, 'Jupiter'), (5, 'Moon')]
5
```

rowcount rises as rows are fetched. fetchall() gave three rows because two had already gone.

### What comes back when there is nothing

| Situation | fetchone() | fetchall() |
| --- | --- | --- |
| No row matches | None | [] |
| All rows fetched one by one | None | [] |
| Rows still waiting | the next tuple | list of all that wait |

Asking for another row with fetchone() *after* fetchall() is not dependable: on our server the connector's default cursor raised "No result set available", while its pure-Python and buffered cursors gave None. In an output question write None; in a program do not do it.

### When to trust rowcount

| After | rowcount means |
| --- | --- |
| INSERT, UPDATE, DELETE | Rows really changed |
| SELECT, before any fetch | Nothing useful yet: we saw 0, and -1 in pure-Python mode |
| SELECT, after fetchall() | Rows fetched in all |
| UPDATE to the value already there | 0, since nothing changed |

So `if cur.rowcount == 0` straight after a SELECT is a mistake. Fetch first, then test.

### Program 3. Search by member

***Program 3**search*

```
# Program 3: search by member
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root",
                              password="your_password",
                              database="skyclub")
cur = con.cursor()
name = input("Member: ")
cur.execute("SELECT object, stars, seen_on FROM sighting "
            "WHERE member = %s", (name,))
data = cur.fetchall()
if cur.rowcount == 0:
    print("Nothing found for", name)
for obj, stars, day in data:
    print(obj, stars, day)
con.close()
```

***Two runs**MySQL*

```
Member: Ira
Saturn 5 2026-10-03
Pleiades 3 2026-10-17
Moon None 2026-11-21

Member: Kabir
Nothing found for Kabir
```

`(name,)` needs its comma. Without it the brackets are only brackets, and the connector complains that a str is not a list, tuple or dict.

Part 3. Changing rows

## Python SQL connectivity programs for Class 12: update, delete, report

An insert, update or delete is yours alone until commit(). The programs below change the same table, in the order you see them.

### Program 4. Update a rating

***Program 4**update*

```
# Program 4: change the stars given to one sighting
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root",
                              password="your_password",
                              database="skyclub")
cur = con.cursor()
sno = int(input("Sighting number: "))
stars = int(input("New stars: "))
cur.execute("UPDATE sighting SET stars = %s WHERE sno = %s",
            (stars, sno))
con.commit()
if cur.rowcount == 1:
    print("Updated.")
else:
    print("No row was changed.")
con.close()
```

***Three runs**MySQL*

```
Sighting number: 5
New stars: 4
Updated.

Sighting number: 5
New stars: 4
No row was changed.

Sighting number: 40
New stars: 4
No row was changed.
```

The second run found sighting 5 but it already had 4 stars, so nothing changed. rowcount cannot tell that apart from a number that does not exist. To know which, SELECT first, as Program 5 does.

### Program 5. Delete, after asking

***Program 5**delete*

```
# Program 5: delete after asking
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root",
                              password="your_password",
                              database="skyclub")
cur = con.cursor()
sno = int(input("Sighting number: "))
cur.execute("SELECT object, member FROM sighting WHERE sno = %s",
            (sno,))
row = cur.fetchone()
if row is None:
    print("No such sighting.")
else:
    sure = input("Delete " + row[0] + " by " + row[1] + "? (y/n) ")
    if sure == "y":
        cur.execute("DELETE FROM sighting WHERE sno = %s", (sno,))
        con.commit()
        print("Deleted:", cur.rowcount)
con.close()
```

***Two runs**MySQL*

```
Sighting number: 2
Delete Moon by Dev? (y/n) y
Deleted: 1

Sighting number: 2
No such sighting.
```

sno is the primary key, so at most one row can come back and fetchone() is enough.

### What does commit() do? Proof with two connections

Most books say commit saves the change. This program shows it: a second connection counts the rows before and after.

***Commit test**two connections*

```
import mysql.connector

def open_club():
    """Return a new connection to skyclub."""
    return mysql.connector.connect(host="localhost", user="root",
                                   password="your_password",
                                   database="skyclub")

def count_rows():
    """Count the sightings as a separate program would."""
    other = open_club()
    cur = other.cursor()
    cur.execute("SELECT COUNT(*) FROM sighting")
    number = cur.fetchone()[0]
    other.close()
    return number

con = open_club()
cur = con.cursor()
cur.execute("INSERT INTO sighting VALUES (%s, %s, %s, %s, %s)",
            (6, "Mars", "Dev", 2, "2026-11-22"))
print("Rows affected:", cur.rowcount)
print("Another program counts:", count_rows())
con.commit()
print("After commit it counts:", count_rows())
con.close()
```

***Output**MySQL*

```
Rows affected: 1
Another program counts: 4
After commit it counts: 5
```

Before commit the new row exists only inside its own connection. We also closed a connection without committing: the row it had inserted was gone.

### Program 6. A report with fetchone in a loop

***Program 6**GROUP BY*

```
# Program 6: sightings and average stars for each member
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root",
                              password="your_password",
                              database="skyclub")
cur = con.cursor()
cur.execute("SELECT member, COUNT(*), AVG(stars) FROM sighting "
            "GROUP BY member ORDER BY member")
row = cur.fetchone()
while row is not None:
    print(row[0], row[1], float(row[2]))
    row = cur.fetchone()
con.close()
```

***Output**MySQL*

```
Dev 1 2.0
Ira 3 4.0
Zoya 1 5.0
```

AVG and SUM arrive as Decimal objects. Without `float()` a printed row would show `Decimal('4.0000')`, which surprises people in the lab.

Programs 1, 3, 4 and 5 cover the four operations schools expect in the report file. Build yours on a different table; the employee version is in [the practical file guide](/blog/python-practical-file-class-12). To see all of it in one application, open [the Class 12 project in Python and MySQL](/cbse-class-12-computer-science-project-python-mysql).

Part 4. Values in a query

## Why use %s and not format() in a Python MySQL query?

Both are in the syllabus. With %s the connector places each value safely; with format() you build the text yourself, quotes included, and a single apostrophe can break it.

***Same search, two ways**%s and format()*

```
# try three kinds of typed name in two kinds of query
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root",
                              password="your_password",
                              database="skyclub")
cur = con.cursor()
name = input("Member: ")
try:
    q = "SELECT sno FROM sighting WHERE member = '{}'"
    cur.execute(q.format(name))
    print("format():", cur.fetchall())
except mysql.connector.Error as problem:
    print("format(): error", problem.errno)
cur.execute("SELECT sno FROM sighting WHERE member = %s", (name,))
print("%s      :", cur.fetchall())
con.close()
```

***Three runs**MySQL*

```
Member: Ira
format(): [(1,), (3,), (5,)]
%s      : [(1,), (3,), (5,)]

Member: D'Cruz
format(): error 1064
%s      : []

Member: x' OR '1'='1
format(): [(1,), (3,), (4,), (5,), (6,)]
%s      : []
```

The last run is an SQL injection: typed text became part of the query and returned every row. With %s it was only a strange name that nobody has.

### Rules for %s

Always %s, even for an INT or a DATE. Never put quotes round it. Values go in a tuple as the second argument of `execute()`.

### Rules for format()

Put quotes round `{}` for text and dates, none for numbers. `format()` finishes before `execute()` sees the string.

### Not for names

%s stands for a value. `SELECT * FROM %s` fails, since a table name would be sent inside quotes.

### A pattern with LIKE

Put the wildcard inside the value: `cur.execute("SELECT sno FROM sighting WHERE object LIKE %s", ("M%",))`. On the table as it now stands this finds sightings 5 and 6, Moon and Mars.

Part 5. When it breaks

## MySQL connector errors in Class 12, and what each one means

Read the number first. It tells you whether the fault is in the connection, the query or the data, and the message then names the word to fix.

| You see | The cause | The cure |
| --- | --- | --- |
| `ModuleNotFoundError: No module named 'mysql.conector'` | Misspelt, or not installed in the Python you are running | Check the spelling of connector, then install mysql-connector-python |
| `2003` Can't connect to MySQL server | The server is not running, or the port is wrong | Start the MySQL service |
| `1045` Access denied for user | Wrong user or password | Try the same pair in the MySQL client |
| `1049` Unknown database 'skyklub' | Name misspelt, or never created | SHOW DATABASES |
| `1146` Table 'skyclub.sightings' doesn't exist | One letter too many | SHOW TABLES |
| `1054` Unknown column 'Ira' in 'where clause' | format() without quotes round a text value | Add the quotes, or use %s |
| `1064` You have an error in your SQL syntax | Misspelt keyword, stray quote, quoted %s | Look at the text after "near" |
| `1062` Duplicate entry '1' for key | Primary key already used | Choose another value or catch the error |
| `1406` Data too long for column | Text longer than VARCHAR(n) | Check the length before inserting |
| `1292` Incorrect date value: '08-11-2026' | Date not in YYYY-MM-DD form | Write 2026-11-08 |
| Not enough parameters for the SQL statement | More %s than values | Count both |
| Not all parameters were used in the SQL statement | More values than %s, or %d written for %s | Use one %s for each value |
| Unread result found | A new query, commit or close on the cursor while rows of a SELECT were still waiting | Fetch them all before the next statement |

### Program 7. Catch the error and stay polite

***Program 7**try, except, finally*

```
import mysql.connector
try:
    con = mysql.connector.connect(host="localhost", user="root",
                                  password="your_password",
                                  database="skyclub")
    cur = con.cursor()
    cur.execute("INSERT INTO sighting VALUES (%s, %s, %s, %s, %s)",
                (1, "Mars", "Dev", 3, "2026-11-22"))
    con.commit()
    print("Saved.")
except mysql.connector.Error as problem:
    print("Not saved:", problem)
finally:
    print("Finished.")
```

***Output**MySQL*

```
Not saved: 1062 (23000): Duplicate entry '1' for key 'sighting.PRIMARY'
Finished.
```

`mysql.connector.Error` is the general class. It catches every numbered error in the table above, but not a misspelt import.

The try block itself is taught on [exception handling for Class 12](/cbse-class-12-computer-science-exception-handling). If the query is what fails, practise it alone first on [Class 12 SQL questions](/cbse-class-12-computer-science-sql-queries).

Part 6. On paper

## Interface of Python with MySQL, Class 12: 4-mark answers, marked by step

Question 35 of the 2026-27 sample paper asks for a complete program, and its marking scheme pays for six separate things. Five of them are the same in every answer you will ever write.

### Where the 4 marks go

| Step in the official scheme | Marks |
| --- | --- |
| Importing the connector | 1/2 |
| Creating the connection | 1/2 |
| Creating the cursor | 1/2 |
| The query | 1 |
| Executing it, with commit | 1 |
| Closing the connection | 1/2 |

That scheme is for an UPDATE. For a SELECT there is nothing to commit, so fetch and display the rows in its place; CBSE has not printed a scheme for that form in this paper.

### Table for the questions

| tno | brand | aperture | room |
| --- | --- | --- | --- |
| 21 | Orbit | 70 | Lab |
| 22 | Nova | 130 | Roof |
| 23 | Orbit | 114 | Roof |
| 24 | Zenith | 50 | Store |
| 25 | Pulsar | 60 | Store |

Table telescope in the database skyclub: tno and aperture are integers, brand and room are strings. Host localhost, user root, password your_password.

1. **1.** Write a Python-MySQL program to display brand and aperture of telescopes with an aperture above 100. **(4 marks)**Answer

  ***Answer 1**select*

  ```
  import mysql.connector
  con = mysql.connector.connect(host="localhost", user="root",
                                password="your_password",
                                database="skyclub")
  cur = con.cursor()
  cur.execute("SELECT brand, aperture FROM telescope "
              "WHERE aperture > 100")
  for brand, aperture in cur.fetchall():
      print(brand, aperture)
  cur.close()
  con.close()
  ```

  Printed: Nova 130, then Orbit 114.
2. **2.** Write a program that accepts the details of one telescope from the user and adds them to the table. **(4 marks)**Answer

  ***Answer 2**insert*

  ```
  import mysql.connector
  con = mysql.connector.connect(host="localhost", user="root",
                                password="your_password",
                                database="skyclub")
  cur = con.cursor()
  tno = int(input("Number: "))
  brand = input("Brand: ")
  aperture = int(input("Aperture: "))
  room = input("Room: ")
  cur.execute("INSERT INTO telescope VALUES (%s, %s, %s, %s)",
              (tno, brand, aperture, room))
  con.commit()
  print("Telescope added.")
  cur.close()
  con.close()
  ```

  Run with 26, Nova, 90 and Lab it printed "Telescope added." Use int() for the integer columns; the tuple keeps the column order.
3. **3.** Write a program to delete telescopes kept in Store with an aperture below 60, and print how many were deleted. **(4 marks)**Answer

  ***Answer 3**delete*

  ```
  import mysql.connector
  con = mysql.connector.connect(host="localhost", user="root",
                                password="your_password",
                                database="skyclub")
  cur = con.cursor()
  cur.execute("DELETE FROM telescope WHERE room = 'Store' "
              "AND aperture < 60")
  con.commit()
  print("Deleted:", cur.rowcount)
  cur.close()
  con.close()
  ```

  Printed: Deleted: 1. Pulsar at exactly 60 stays. rowcount belongs to the cursor.
4. **4.** This program should move every telescope on the Roof to a room typed by the user. Find four mistakes. **(practice)**

  ***With mistakes**do not run*

  ```
  import mysql.connector
  con = mysql.connector.connect(host="localhost", user="root",
                                password="your_password",
                                database="skyclub")
  cur = con.Cursor()
  room = input("Move Roof telescopes to: ")
  q = "UPDATE telescope SET room = {} WHERE room = 'Roof'"
  cur.execute(q.format(room))
  cur.commit()
  print(cur.rowcount(), "moved")
  con.close()
  ```

  Answer`cursor()` in small letters; quotes round `{}`, as room is text; `con.commit()`; and `rowcount` without brackets.

  ***Answer 4**corrected*

  ```
  import mysql.connector
  con = mysql.connector.connect(host="localhost", user="root",
                                password="your_password",
                                database="skyclub")
  cur = con.cursor()
  room = input("Move Roof telescopes to: ")
  q = "UPDATE telescope SET room = '{}' WHERE room = 'Roof'"
  cur.execute(q.format(room))
  con.commit()
  print(cur.rowcount, "moved")
  con.close()
  ```

  Run with Terrace on the table after Answers 2 and 3, it printed "2 moved".
5. **5.** On the original five rows, predict the output. **(practice)**

  ***Question 5**predict*

  ```
  import mysql.connector
  con = mysql.connector.connect(host="localhost", user="root",
                                password="your_password",
                                database="skyclub")
  cur = con.cursor()
  cur.execute("SELECT tno, brand FROM telescope ORDER BY aperture")
  a = cur.fetchone()
  b = cur.fetchone()
  rest = cur.fetchall()
  print(a[1], b[1])
  print(len(rest), cur.rowcount)
  print(rest[-1])
  con.close()
  ```

  Answer

  ***Output**MySQL*

  ```
  Zenith Pulsar
  3 5
  (22, 'Nova')
  ```

  Ascending aperture is 50, 60, 70, 114, 130. Two rows went to a and b, three remained, and five were fetched in all.
6. **6.** Fill in the blanks so that the program counts telescopes of a brand typed by the user. **(practice)**

  ***Question 6**four blanks*

  ```
  import mysql.connector
  con = mysql.connector.________(host="localhost", user="root",
                                 password="your_password",
                                 database="skyclub")
  cur = con.________()
  brand = input("Brand: ")
  cur.execute("SELECT * FROM telescope WHERE brand = %s", ________)
  data = cur.________()
  print(len(data), "found")
  con.close()
  ```

  Answer`connect`, `cursor`, `(brand,)`, `fetchall`.

  ***Answer 6**complete*

  ```
  import mysql.connector
  con = mysql.connector.connect(host="localhost", user="root",
                                password="your_password",
                                database="skyclub")
  cur = con.cursor()
  brand = input("Brand: ")
  cur.execute("SELECT * FROM telescope WHERE brand = %s", (brand,))
  data = cur.fetchall()
  print(len(data), "found")
  con.close()
  ```

  With Orbit it printed "2 found".

### We break it on purpose

In class the teacher spoils one line of a working program and you read the message aloud, name the fault and repair it.

### Six ticks

Each written answer is marked against the six steps. Whoever forgets the closing line sees that half mark missing until it stops happening.

### Your laptop, your server

Installation trouble is handled on your own machine, so the programs you show your school are ones you have run.

Next: the full paper around this question on [the 2026-27 sample paper](/cbse-class-12-computer-science-sample-paper-2026-27), and the spoken version of it in [Class 12 CS viva questions](/cbse-class-12-computer-science-viva-questions).

One to one, at your own timing

## Some topics need your own screen shared

When a connection fails, the reason is on your computer and nowhere else. That is why this is taught personalised one to one, on days and at a time that you decide. Try it through a priority demo, a full class whose fee is adjusted against the first month when you enrol, or start with a free demo class. Billing is month by month, admission costs nothing, and stopping at a month end is always allowed.

Before you enrol · Try a class

### Priority demo, at a slot you pick

a full live class of about 45 to 60 minutes

- Python and MySQL talking to each other on your computer
- One insert and one search program written by you
- A broken program repaired from its error message
- A written skill report on Python, SQL and the link

[Book a priority demo](/book-demo)

The classes · Choose your own timing

### Personalised one to one

₹4,999

per month, 4 private classes, fully flexible timing

- Four report-file programs of your own, checked line by line
- The 4-mark answer practised until no step is missed
- Weak SQL or weak functions repaired first if they are the cause
- Project database work guided at your pace

Ask for a personalised plan

Tell us your operating system and whether MySQL is already installed when you book. If it is not, part of the first class sets it up; if your school uses another tool to run Python, we work in that one.

Studying outside India?

## Connectivity classes for CBSE schools overseas

From Salalah to Kuala Lumpur, the 083 paper carries the same Python-MySQL question. Classes follow your local day, including weekends if that is when the laptop is free.

| Where you live | Time difference | Usual class window, local time | Format |
| --- | --- | --- | --- |
| India every Indian city | Indian time | Any time you choose | Personalised 1-on-1 |
| UAE and Oman Dubai, Abu Dhabi, Sharjah, Muscat | 1 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Saudi Arabia, Qatar, Kuwait, Bahrain Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama | 2 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Nepal Kathmandu | 15 min ahead of India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Ethiopia and East Africa Addis Ababa and East Africa Time | 2 h 30 min behind India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Singapore and Malaysia Singapore, Kuala Lumpur | 2 h 30 min ahead of India | 3:30 PM to 9:00 PM | Personalised 1-on-1 |

Remote help suits this topic well: the teacher sees the same red error text you do, and you do the typing that fixes it.

What families say

## Rated 4.9 across 547 Google reviews

Real reviews from real families. We neither write nor commission them.

★★★★★

"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."

Ria Mukherjee

Parent

★★★★★

"Modern Age Coders has been a game-changer for me. I struggled to grasp IT concepts and coding before joining, but their classes transformed everything. I can now confidently write complex programs with ease."

Samriddha Mondal

Student

★★★★★

"One of the most wonderful education centres out there. Education is not limited to school syllabus but focuses on skill development."

Vansh Agarwal

Student

★★★★★

"My child Dhairya is really enjoying the Modern Age Coders classes. This is his first online class and he eagerly looks forward to it. I can already see his improvement, and the teachers are very cooperative."

Sonam Oswal

Parent of Dhairya

★★★★★

"Modern Age Coders have wonderful teachers who teach in a clear, easy and practical way. The teacher boosts students' confidence and inspires them to learn without hesitation."

Sonu Goyal

Parent

★★★★★

"I highly recommend this computer coding class! The teachers are incredibly knowledgeable and passionate about coding."

Ritu Kedia

Parent

The rest of the Class 12 series

## More pages for Class 12 students

Every page in the CBSE Class 12 Computer Science series, grouped by what you need.

### Practicals, project and viva

- [Class 12 CS viva questions](/cbse-class-12-computer-science-viva-questions)
- [Class 12 CS project with source code](/cbse-class-12-computer-science-project-python-mysql)
- [Class 12 CS project topics](/cbse-class-12-computer-science-project-topics)

### Exam, papers and marks

- [Class 12 CS sample paper practice](/cbse-class-12-computer-science-sample-paper-2026-27)
- [Class 12 CS exam date, pattern and marks](/cbse-class-12-computer-science-paper-pattern-and-marking-scheme)
- [Class 12 CS important questions](/cbse-class-12-computer-science-important-questions)

### Questions and practice

- [Class 12 CS MCQ test](/cbse-class-12-computer-science-mcq-test)
- [Class 12 CS output questions](/cbse-class-12-computer-science-output-questions)
- [Class 12 CS case study questions](/cbse-class-12-computer-science-case-study-questions)
- [Class 12 CS SQL questions](/cbse-class-12-computer-science-sql-queries)

### Chapter by chapter

- [Functions in Python Class 12](/cbse-class-12-computer-science-functions)
- [Exception handling Class 12](/cbse-class-12-computer-science-exception-handling)
- [Text file handling Class 12](/cbse-class-12-computer-science-file-handling)
- [CSV and binary files Class 12](/cbse-class-12-computer-science-csv-and-binary-files)
- [Stack Class 12 Computer Science](/cbse-class-12-computer-science-stack)
- [Computer networks Class 12](/cbse-class-12-computer-science-computer-networks)

### Notes, revision and help

- [Class 12 CS syllabus 2026-27](/cbse-class-12-computer-science-syllabus-2026-27)
- [Class 12 CS notes](/cbse-class-12-computer-science-notes)
- [Class 12 CS revision plan](/cbse-class-12-computer-science-revision-plan)
- [Class 12 CS crash course](/cbse-class-12-computer-science-crash-course)

**CBSE Class 12 Informatics Practices (065):** [Class 12 IP practical file](/cbse-class-12-informatics-practices-practical-file)  [Class 12 IP project with source code](/cbse-class-12-informatics-practices-project)  [Class 12 IP sample paper practice](/cbse-class-12-informatics-practices-sample-paper-2026-27)  [Class 12 IP important questions](/cbse-class-12-informatics-practices-important-questions)

**CBSE Class 12 Information Technology (802):** [IT 802 practical and project file](/cbse-class-12-it-802-practical-and-project-file)  [IT 802 Java notes and programs](/cbse-class-12-it-802-java-programs)  [IT 802 notes](/cbse-class-12-it-802-notes)

**CBSE Class 11 CS, IP and AI:** [Class 11 CS practical file](/cbse-class-11-computer-science-practical-file)  [Class 11 IP practical file](/cbse-class-11-informatics-practices-practical-file)  [CS or IP in Class 11](/computer-science-or-informatics-practices-class-11)

**ISC Computer Science (868):** [ISC Class 12 CS syllabus 2027](/isc-class-12-computer-science-syllabus-2027)  [ISC Class 12 CS practice paper](/isc-class-12-computer-science-specimen-paper-practice)  [ISC Class 12 practical questions solved](/isc-class-12-computer-science-practical-questions)  [ISC Boolean algebra and K-maps](/isc-class-12-computer-science-boolean-algebra)

**Program lists with output:** [Class 12 CS practical file](/blog/python-practical-file-class-12)  [20 Python programs for Class 12](/blog/python-programs-for-cbse-class-12)  [Menu-driven programs in Python](/blog/how-to-build-menu-driven-program-in-python)

Connectivity, answered

## Python and MySQL: what students search for

### What are the steps to connect Python with MySQL in Class 12?

Import mysql.connector, open a connection with connect(), create a cursor with cursor(), send the SQL with execute(), then commit() for a change or fetch the rows for a SELECT, and close the connection. Four steps sit between the import and the close: connect, cursor, execute, commit or fetch.

### What is mysql.connector in Class 12 Computer Science?

It is a Python module that lets a program talk to a MySQL server. It comes from the package mysql-connector-python, which is installed separately from both Python and MySQL. Its connect() function returns the connection object that every other step depends on.

### What is the difference between fetchone and fetchall?

fetchone() returns the next row as a tuple, or None when no row is left. fetchall() returns a list of all rows not yet fetched, or an empty list. After one fetchone() on five rows, fetchall() gives the other four.

### What is rowcount in Python MySQL connectivity?

rowcount is an attribute of the cursor. After INSERT, UPDATE or DELETE it is the number of rows changed. After a SELECT it counts the rows fetched so far, so it is useful only once you have fetched. It takes no brackets.

### Why is commit() needed, and is it needed for SELECT?

commit() makes an INSERT, UPDATE or DELETE permanent and visible to other programs. Without it the change is lost when the connection closes. A SELECT changes nothing, so it needs no commit.

### What is a cursor in Python MySQL?

A cursor is the object, made by con.cursor(), through which queries are executed and rows are read back. It remembers how far you have read, which is why each fetch continues from where the last one stopped.

### Should I use %s or format() in the board exam?

The syllabus names both, so either is fine when written correctly. %s with a tuple is safer because you never type quotes round values. With format(), text and date values need quotes inside the query string.

### How many marks is Python MySQL connectivity in Class 12?

In the CBSE 2026-27 sample paper it is Question 35, for 4 marks out of 70. It also appears in the practical: the report file needs at least four Python to SQL programs, and many projects and viva conversations rest on it.

### Why do I get Unread result found in MySQL connector?

You ran a SELECT, did not fetch every row, and then sent another query on the same connection. Fetch the remaining rows first, for example with fetchall(), or create the cursor with buffered=True, which is extra to the syllabus.

### Can I learn Python MySQL connectivity one to one?

Yes. Modern Age Coders teaches it live and personalised one to one at your own days and timing, on your own computer. A priority demo is a full class of about 45 to 60 minutes with a written skill report, and its fee is adjusted against the first month. A free demo class is also offered.

Start

## Get the first row out of your own database.

Use the free demo class to show us where you are stuck: a module that will not import, a password refused, or a 4-mark answer that keeps losing half marks.

In a **priority demo** you get the whole class: connection working, one program written from nothing, one error hunted down, and a written skill report. It happens at a slot you select, and enrolling adjusts the fee against the first month.

While you wait, the menu around these programs is explained in [building a menu-driven program in Python](/blog/how-to-build-menu-driven-program-in-python).

[WhatsApp us](https://wa.me/919123366161?text=Hello%20Modern%20Age%20Coders.%20I%20want%20one%20to%20one%20classes%20on%20Python%20MySQL%20connectivity%20for%20CBSE%20Class%2012%20Computer%20Science%20083.) · [+91 91233 66161](tel:+919123366161) · [connect@modernagecoders.com](mailto:connect@modernagecoders.com)

Every class is live video. The form requests a callback and reserves nothing.

### Want it sooner? Book a priority demo

A full live class of about 45 to 60 minutes at a slot you pick, with a written skill report and learning roadmap on WhatsApp afterwards. The fee is adjusted against your first month if you enrol.

[Book a priority demo](/book-demo)

## Keep exploring Modern Age Coders

### By class and age

- [Class 12 IP Computer Networks Notes: Unit 3 for 2026-27](/cbse-class-12-informatics-practices-computer-networks)
- [Class 12 IP Crash Course 2027: Live One to One Classes](/cbse-class-12-informatics-practices-crash-course)
- [DataFrame Class 12 IP: Notes, loc and iloc, Programs](/cbse-class-12-informatics-practices-dataframe)
- [Class 12 IP Data Visualization: Line, Bar, Histogram](/cbse-class-12-informatics-practices-matplotlib-charts)
- [Class 12 IP MCQ with Answers 2026-27: a 40-Question Test](/cbse-class-12-informatics-practices-mcq-test)
- [Pandas Series Class 12 IP: Notes, Outputs and Questions](/cbse-class-12-informatics-practices-pandas-series)
- [File Handling Class 12 Computer Science: Text File Notes](/cbse-class-12-computer-science-file-handling)
- [Class 11 IP Sample Paper 2026-27 With Solution, 70 Marks](/cbse-class-11-informatics-practices-sample-paper)
- [Number System Class 11 Computer Science: Conversions, Logic](/cbse-class-11-number-system-conversion)
- [Online Coding and Python Classes in Stourbridge](/online-coding-and-python-classes-in-stourbridge)
- [Exception Handling in Python Practice](/resources/python/exception-handling/practice)
- [Setting Up MySQL and Your First Query Practice](/resources/sql/setting-up-mysql-and-first-query/practice)

### Learn more

- [Informatics Practices (IP) Class 11-12: CBSE Python & SQL](/courses/cbse-informatics-practices-ip-class-11-12-python-pandas-sql-complete-course)
- [AI and Python Classes for Teens in Fredericton, NB](/ai-and-python-classes-for-teens-in-fredericton)
- [Data Analysis Course: Excel, SQL, Python & BI](/courses/data-analysis-mastery-course-college)
- [Python Turtle Not Working? Real Errors and Fixes](/python-turtle-not-working)

### Free resources

- [Python Tutorial for Beginners: Complete Guide](/resources/python)
- [Self Joins and Multi-Table Queries](/resources/sql/self-joins-and-multi-table)
- [Scope, LEGB Rule, and Closures](/resources/python/scope-and-closures)
- [Triggers and Scheduled Events](/resources/sql/triggers-and-events)

### From the blog

- [Python Tutorials & Guides](/blog/topic/python)
- [Python Programs for Class 11 CBSE (CS and IP) With Output](/blog/python-programs-for-class-11)
- [Cambridge 9618 Paper 4: Python, Java or Visual Basic?](/blog/cambridge-9618-paper-4-python-java-or-visual-basic)
- [Python Code Examples: 35 Simple Programs With Output](/blog/python-basic-programs-for-beginners)

### Start here

- [Modern Age Coders pricing, one honest price per plan](/pricing)
- [How Modern Age Coders teaches, small batches and real projects](/how-we-teach)

---

*Canonical: https://learn.modernagecoders.com/cbse-class-12-computer-science-python-mysql-connectivity*
