Connecting Python with MySQL: connect(), cursor(), execute() and close() (Class 12 Computer Science)
Updated 17 October 2026 · Fact-checked
To use MySQL from Python, import mysql.connector, call connect(host, user, passwd, database) to get a connection object, call cursor() on it to get a cursor, run SQL with cursor.execute(query), and finally close the connection with close(). A wrong password or unreachable server raises mysql.connector.Error.
Follow the numbered steps: connect() builds the connection, cursor() travels along it, and execute() sends SQL to the database.
Illustration drawn for QuestionBuddy.
Understand Connecting Python to MySQL: connect(), cursor() and execute()
Python talks to a MySQL database through the module mysql.connector, which must be installed and the MySQL server must be running. The programs of this chapter use a database school with the table STUDENT(RollNo INT, Name VARCHAR, Class CHAR(3), Marks INT, City VARCHAR) holding five rows:
| RollNo | Name | Class | Marks | City |
|---|---|---|---|---|
| 1 | Asha | 12A | 88 | Delhi |
| 2 | Ravi | 12B | 64 | Mumbai |
| 3 | Meena | 12A | 79 | Chennai |
| 4 | Joy | 12C | 91 | Delhi |
| 5 | Kiran | 12B | 55 | Pune |
The six steps of every connectivity program.
1. Import the module: import mysql.connector (usually with an alias, as sqltor).
2. Connect: con = mysql.connector.connect(host="localhost", user="root", passwd="admin123", database="school") returns a connection object.
3. Create a cursor: cur = con.cursor().
4. Execute a query: cur.execute("SELECT * FROM STUDENT").
5. Process the result or commit the change (next two topics).
6. Close: con.close().
Connection arguments. host is the server name ("localhost" for the same computer), user and passwd (the keyword password also works) are the account details, and database is the database to use. The password in the examples is a placeholder.
Checking the connection. con.is_connected() returns True when the connection is open. A failed login does not return False: connect() raises mysql.connector.Error, so a safe program uses try-except.
import mysql.connector as sqltor
try:
con = sqltor.connect(host="localhost", user="root", passwd="admin123", database="school")
if con.is_connected():
print("Connected")
con.close()
except sqltor.Error:
print("Could not connect")With correct details this prints Connected; with a wrong password it prints Could not connect.
The cursor. A cursor is the object through which SQL statements are sent and results are read. cur.execute(sql) sends one statement. After a SELECT the rows wait inside the cursor for fetching. The cursor can also take values separately: cur.execute(sql, values), used with %s (see the third topic).
Connecting Python to MySQL: connect(), cursor() and execute(): key facts
- Six steps
- import mysql.connector
- connect(host, user, passwd, database)
- con.cursor()
- cur.execute(query)
- fetch or commit
- con.close()
- Every board program follows this order.
- connect() arguments
host server, localhost user account name passwd password database database to use - The password is never printed.
- Connection and cursor
con.is_connected() True if open con.cursor() creates a cursor cur.execute(sql) runs a query con.close() ends the connection - A wrong login raises mysql.connector.Error.
- Alias
- import mysql.connector as sqltor
- then sqltor.connect(...)
- sqltor.Error
- Any alias is fine; use it consistently.
How to answer Connecting Python to MySQL: connect(), cursor() and execute() questions
For a connectivity program, write the six steps top to bottom and check names.
- 1Import mysql.connector (with an alias) at the top.
- 2Call connect with host, user, passwd and database; keep the result in a variable such as con.
- 3Create the cursor with cur = con.cursor() (do not forget the brackets).
- 4Put the SQL statement in a string and pass it to cur.execute().
- 5Add the fetch loop for SELECT, or con.commit() for INSERT, UPDATE and DELETE.
- 6Close the connection at the end; wrap steps in try-except if a failed connection must be handled.
Connecting Python to MySQL: connect(), cursor() and execute() in real life
The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Reading the school database from a program
Suppose a school office wants a Python program to read its database instead of typing SQL in the MySQL window.
Which two objects must the program create before it can run a query?
Try it first, then show the solutionSolution
- A connection object from connect(), which opens the link with the server.
- A cursor from con.cursor(), which carries each SQL statement and holds its result.
Answer: A connection (con) and a cursor (cur).
Memory hook: The connection is the phone line; the cursor is the person who speaks on it.
Wrong password
Suppose the password given to connect() is mistyped.
What does the program do if it has no try-except, and what with one?
Try it first, then show the solutionSolution
- connect() raises mysql.connector.Error, so the program stops with an error message.
- With try-except it can print a friendly message such as Could not connect.
Answer: It stops with an error; with try-except it prints a message instead.
Memory hook: A locked door does not return "no"; it raises an alarm.
Tricks to remember Connecting Python to MySQL: connect(), cursor() and execute()
Short memory aids. Say each one aloud once, then use it on a question the same day.
I-C-C-E-F-C
Import, Connect, Cursor, Execute, Fetch or commit, Close.
Use it when: The sequence of steps.
Connection is the line, cursor is the speaker
You need both to make a call.
Use it when: Connection versus cursor.
Brackets on cursor()
cursor is a method; call it with ().
Use it when: Common syntax error.
Close the door
Always end with con.close().
Use it when: Last step.
Connecting Python to MySQL: connect(), cursor() and execute(): solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: Module name · 1 mark · MCQBoard level
Which module is imported in Python to connect to a MySQL database?
(a) mysql.client (b) mysql.connector (c) sql.connect (d) pymysql.lib
Try it first, then show the solutionSolution
- The syllabus uses the mysql.connector module.
Answer: (b) mysql.connector
Example 2: Steps · 2 marks · Short answerBoard level
Write the steps, in order, for executing a SELECT query on a MySQL table from Python.
Try it first, then show the solutionSolution
- Import mysql.connector; connect with connect(); create a cursor with cursor(); (1 mark)
- run the query with execute(); fetch the rows with fetchone() or fetchall(); close the connection with close(). (1 mark)
Answer: Import, connect, cursor, execute, fetch, close.
Example 3: Connected or not · 3 marks · Short answerHarder board level
Write a program that connects to the database school (host localhost, user root, password admin123) and prints Connected if the connection is open, and Could not connect if the server refuses the login.
Try it first, then show the solutionSolution
(2 marks for import, connect with four arguments and try-except)import mysql.connector as sqltor try: con = sqltor.connect(host="localhost", user="root", passwd="admin123", database="school") if con.is_connected(): print("Connected") con.close() except sqltor.Error: print("Could not connect")- With valid details the output is Connected; a failed login is caught by except and prints Could not connect. (1 mark)
Answer: Connected (valid details) or Could not connect (login refused)
Example 4: Run a query and print the rows · 3 marks · Short answerHarder board level
Complete the program so that it prints the name and city of every student in roll number order:
import mysql.connector as sqltor
conn = sqltor.connect(host="localhost", user="admin", passwd="admin123", database="school")
cur = ____(1)____
cur.____(2)____("SELECT Name, City FROM STUDENT ORDER BY RollNo")
for row in cur:
print(row)
conn.____(3)____Try it first, then show the solutionSolution
- (1) conn.cursor() (1 mark)
- (2) execute (1 mark)
- (3) close() (1 mark). The loop prints ('Asha', 'Delhi') and then the other four rows, one tuple per line.
Answer: (1) conn.cursor() (2) execute (3) close()
Example 5: Case: debugging a program · 4 marks · Case-basedHOTS / competency
Suppose a student writes this program and gets an error on the second line after the connection:
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="admin123", database="school")
cur = con.cursor
cur.execute("SELECT Name FROM STUDENT")
print(cur.fetchone())(i) Identify the mistake. (1 mark)
(ii) Write the corrected line. (1 mark)
(iii) What is printed by the corrected program for the first row? (1 mark)
(iv) Which statement is missing at the end of the program? (1 mark)
Try it first, then show the solutionSolution
- (i) cursor is a method; writing con.cursor without brackets stores the method itself, so cur.execute is not found.
- (ii) cur = con.cursor()
- (iii) fetchone() gives the first row as a tuple: ('Asha',) when rows come in table order.
- (iv) con.close() to close the connection.
Answer: (i) missing brackets (ii) cur = con.cursor() (iii) ('Asha',) (iv) con.close()
Where students lose marks in Connecting Python to MySQL: connect(), cursor() and execute()
The slips examiners see most often, and what to write instead.
Mistake: Writing con.cursor without brackets
cursor is a method; without brackets cur holds the method itself.
Wrong working
cur = con.cursor
Right working
cur = con.cursor()
Do this: Check every method call for ().
Usually costs: 1 mark
Mistake: Executing before creating the cursor
The query is run through the cursor, not the connection.
Wrong working
con.execute("SELECT * FROM STUDENT")
Right working
cur = con.cursor()
cur.execute("SELECT * FROM STUDENT")Do this: Create the cursor, then execute.
Usually costs: 1 mark
Mistake: Forgetting to close the connection
Resources stay open and the board expects the sixth step.
Wrong working
(no close statement)
Right working
con.close()
Do this: End the program with close().
Usually costs: 0.5 mark
Exam tips
- Write the six steps as comments or in this order so the examiner can mark each.
- Use the same alias for the module everywhere (sqltor.connect, sqltor.Error).
- Never print the password; use a placeholder in written answers.
- Use double quotes around SQL that contains single-quoted text.
- Mention that the MySQL server must be running and mysql.connector installed when asked about requirements.
Practice questions on Connecting Python to MySQL: connect(), cursor() and execute()
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
The method of the connection object that creates a cursor is:
(a) connect() (b) cursor() (c) execute() (d) commit()Hint
Think of the object that carries SQL.
Answer
(b) cursor()
Q2 · 1 mark · Very short answerBoard level
Which method closes the connection to the database?
Hint
The last step.
Answer
con.close()
Q3 · 2 marks · Short answerHarder board level
Write the statements to import mysql.connector with the alias m and connect to the database school on localhost as user root with the password pw123.
Hint
Four arguments.
Answer
import mysql.connector as m
con = m.connect(host="localhost", user="root", passwd="pw123", database="school")Q4 · 1 mark · Assertion-reasonHarder board level
Assertion (A): A program that gives a wrong password to connect() simply gets False from is_connected().
Reason (R): connect() raises mysql.connector.Error when the login fails.
(a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.Hint
Is a connection object ever created?
Answer
(d) A is false and R is true: no connection object is returned, so is_connected() is never reached.
Q5 · 3 marks · Short answerHOTS / competency
Suppose a program must print Welcome if the connection is made, but tell the user to check the password when the login fails. Write the code using try-except, and explain why an if-else alone cannot handle the failure.
Hint
The error happens inside connect().
Answer
import mysql.connector as m try: con = m.connect(host="localhost", user="root", passwd="pw", database="school") print("Welcome") con.close() except m.Error: print("Check the password")If the login fails, connect() raises an exception and no connection object exists to test with if-else, so the except block must catch it.
Test your recall
Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.
1.Which module connects Python to MySQL?Show answer
mysql.connector.
2.Which function opens a connection?Show answer
connect().
3.Which method gives a cursor?Show answer
con.cursor().
4.Which method runs an SQL statement?Show answer
cur.execute().
5.What does connect() raise on a failed login?Show answer
mysql.connector.Error.
6.Which method ends the connection?Show answer
close().
Connecting Python to MySQL: connect(), cursor() and execute(): frequently asked questions
What are the steps of Python and MySQL connectivity?
Import mysql.connector, connect with host, user, passwd and database, create a cursor, execute the SQL, fetch results or commit changes, and close the connection.
What is a cursor in Python MySQL connectivity?
A cursor is an object created from the connection that sends SQL statements to the server and holds the rows returned by a SELECT.
What does is_connected() do?
It returns True if the connection to the server is open. A failed login raises an error before it can be used.
Do I need to install anything before running these programs?
Yes. The mysql.connector package must be installed in Python and the MySQL server must be running.