CBSE Class 12 · Computer Science, code 083 · Interface of Python with SQL

Python MySQL connectivity for Class 12, step by step.

Python MySQL connectivity in Class 12 is four steps, and almost every lost mark is a step left out: a cursor never made, a change never committed, a query never executed. This page runs each step on a small sky-watching log, shows what came back, shows what breaks and what the error says, and then writes 4-mark answers the way the marking scheme counts them.

Live one to one · every program run on MySQL · installation help included · a time of your own

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.

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?

FunctionBelongs toWhat it gives back
connect()mysql.connectorA connection object
cursor()connectionA cursor object
execute()cursorNothing you need; rows wait to be fetched
fetchone()cursorOne row as a tuple, or None at the end
fetchall()cursorA list of the rows left, or [] if none
rowcountcursorA number. It is an attribute: no brackets
commit()connectionNothing; the change becomes permanent
close()bothNothing

Writing cur.commit() stops the program: 'CMySQLCursor' object has no attribute 'commit'. Remember it as: the connection commits.

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 1create 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 2display
# 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()
OutputMySQL
(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 testfive 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()
OutputMySQL
(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

Situationfetchone()fetchall()
No row matchesNone[]
All rows fetched one by oneNone[]
Rows still waitingthe next tuplelist 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

Afterrowcount means
INSERT, UPDATE, DELETERows really changed
SELECT, before any fetchNothing useful yet: we saw 0, and -1 in pure-Python mode
SELECT, after fetchall()Rows fetched in all
UPDATE to the value already there0, 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 3search
# 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 runsMySQL
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 4update
# 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 runsMySQL
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 5delete
# 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 runsMySQL
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 testtwo 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()
OutputMySQL
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 6GROUP 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()
OutputMySQL
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. To see all of it in one application, open the Class 12 project in Python and 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 runsMySQL
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 seeThe causeThe cure
ModuleNotFoundError: No module named 'mysql.conector'Misspelt, or not installed in the Python you are runningCheck the spelling of connector, then install mysql-connector-python
2003 Can't connect to MySQL serverThe server is not running, or the port is wrongStart the MySQL service
1045 Access denied for userWrong user or passwordTry the same pair in the MySQL client
1049 Unknown database 'skyklub'Name misspelt, or never createdSHOW DATABASES
1146 Table 'skyclub.sightings' doesn't existOne letter too manySHOW TABLES
1054 Unknown column 'Ira' in 'where clause'format() without quotes round a text valueAdd the quotes, or use %s
1064 You have an error in your SQL syntaxMisspelt keyword, stray quote, quoted %sLook at the text after "near"
1062 Duplicate entry '1' for keyPrimary key already usedChoose another value or catch the error
1406 Data too long for columnText longer than VARCHAR(n)Check the length before inserting
1292 Incorrect date value: '08-11-2026'Date not in YYYY-MM-DD formWrite 2026-11-08
Not enough parameters for the SQL statementMore %s than valuesCount both
Not all parameters were used in the SQL statementMore values than %s, or %d written for %sUse one %s for each value
Unread result foundA new query, commit or close on the cursor while rows of a SELECT were still waitingFetch them all before the next statement

Program 7. Catch the error and stay polite

Program 7try, 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.")
OutputMySQL
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. If the query is what fails, practise it alone first on Class 12 SQL questions.

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 schemeMarks
Importing the connector1/2
Creating the connection1/2
Creating the cursor1/2
The query1
Executing it, with commit1
Closing the connection1/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

tnobrandapertureroom
21Orbit70Lab
22Nova130Roof
23Orbit114Roof
24Zenith50Store
25Pulsar60Store

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 1select
    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 2insert
    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 3delete
    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 mistakesdo 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 4corrected
    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 5predict
    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
    OutputMySQL
    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 6four 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 6complete
    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, and the spoken version of it in Class 12 CS 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

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 liveTime differenceUsual class window, local timeFormat
India
every Indian city
Indian timeAny time you choosePersonalised 1-on-1
UAE and Oman
Dubai, Abu Dhabi, Sharjah, Muscat
1 h 30 min behind India3:00 PM to 9:00 PMPersonalised 1-on-1
Saudi Arabia, Qatar, Kuwait, Bahrain
Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama
2 h 30 min behind India3:00 PM to 9:00 PMPersonalised 1-on-1
Nepal
Kathmandu
15 min ahead of India4:30 PM to 9:00 PMPersonalised 1-on-1
Ethiopia and East Africa
Addis Ababa and East Africa Time
2 h 30 min behind India4:30 PM to 9:00 PMPersonalised 1-on-1
Singapore and Malaysia
Singapore, Kuala Lumpur
2 h 30 min ahead of India3:30 PM to 9:00 PMPersonalised 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.

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.

WhatsApp us · +91 91233 66161 · connect@modernagecoders.com

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

We call within a few hours. No card, no enrolment fee.

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

Keep exploring Modern Age Coders

By class and age

Learn more

Free resources

From the blog

Start here