Connecting Python to MySQLOptional for Informatics Practices
You can write SQL and you can write Python. This chapter joins them: a Python program that stores its data in MySQL instead of in a file. It is the last unit of the Computer Science course, and the one most Class 12 projects are built on.
1Why connect them at all
You have written Python programs that keep their data in a text, binary or CSV file. Those work, but you had to do everything by hand: find a record, keep the file consistent, handle two people using it at once.
MySQL already does all of that. What it cannot do is ask the user questions, print a menu or produce a report. So each side does what it is good at:
The menus, the input, the calculations, the printed report — everything a person interacts with.
Storing the data safely, finding it fast, and enforcing the keys and constraints.
2The connector module
Python cannot talk to MySQL on its own. It needs a connector — a module that knows how to carry a query to the server and bring the answer back. Install it once, from the command prompt and not from inside Python:
pip install mysql-connector-pythonThen import it at the top of the program:
import mysql.connectormysql-connector-python with a hyphen, and import mysql.connector with a dot. They look different because one is the package's name on the internet and the other is its name in Python. Both spellings matter.3Opening the connection
connect() takes four things: which machine the server is on, who you are, your password, and which database you want.
import mysql.connector
con = mysql.connector.connect(
host="localhost",
port=3307,
user="student",
passwd="kv@1234",
database="lambdalab")
print("Connected?", con.is_connected())
con.close()
print("After close:", con.is_connected())Connected? True After close: False
"localhost" means the server is on this same computer. That is the normal case in a school lab.
The MySQL username. In most textbooks and labs this is "root".
The password for that user, set when MySQL was installed. Also spelled password=.
Which database to open — the same thing use lambdalab; does at the prompt.
port out entirely. The practice server these outputs were run against uses 3307, so the line is shown here to keep the program and its output honestly matched. On your machine, delete it.4Checking it actually opened
is_connected() returns True or False. It is worth printing while you are learning, because a program that fails at the very first step is otherwise confusing to debug.
Notice the second line of that output: after con.close() the same call returns False. Closing is not just tidiness — the connection genuinely stops working, and any query after it will fail.
5When the details are wrong
Get the password wrong and connect() raises an exception. This is exactly what the Exception Handling chapter was for:
import mysql.connector
try:
con = mysql.connector.connect(
host="localhost", port=3307,
user="student", passwd="wrong", database="lambdalab")
except mysql.connector.Error as err:
print("Error:", err)Error: 1045 (28000): Access denied for user 'student'@'localhost' (using password: YES)
1045 is the error number to recognise: the username or password is wrong. (using password: YES) tells you a password was sent — if it said NO, you had forgotten the passwd argument altogether.
database= spelling. 2003 — cannot reach the server at all, which usually means MySQL is not running.6The shape of every program in this chapter
Open the connection.
Make the object that carries queries.
Run SQL, and fetch any answer.
Let the connection go.
Steps 2 and 3 are the next lesson. Every program you write for the rest of this chapter has this same skeleton.
7Recap
Once, at the command prompt.
Hyphen to install, dot to import.
Returns a connection object.
Check it opened; let it go when done.
Which statement imports the connector?
What does con.is_connected() return after con.close()?
A program stops with 'Access denied for user … (using password: YES)'. What is wrong?