Python talks to databases through driver modules that follow a common standard, so the steps are almost the same for MySQL, PostgreSQL or SQLite. This section sets up MySQL access and makes the first connection.
The Python DB-API
PEP 249, the Python Database API Specification v2.0, defines a common interface that database drivers follow:
Opens a connection to the database server; returns a connection object
connection.cursor()
Creates a cursor, the object that sends SQL and holds results
cursor.execute(sql, params)
Runs one SQL statement
cursor.fetchone(), fetchmany(n), fetchall()
Read result rows
connection.commit(), rollback()
Keep or undo the current transaction
cursor.close(), connection.close()
Release resources
Installing what you need
MySQL Server: install MySQL Community Server (the current long-term-support release is 8.4) from dev.mysql.com, and set a root password during setup. MySQL Workbench is an optional graphical tool.
The driver: pip install mysql-connector-python (or conda install -c conda-forge mysql-connector-python in Anaconda).
Check: in Python, import mysql.connector should run without error.
Connecting and creating a database
mysql.connector.connect() takes keyword arguments; the common ones are host (the server’s address, "localhost" for your own computer), user, password (passwd is an older alias), and optionally database (the database to use) and port (default 3306).
Key takeaways
PEP 249 (DB-API 2.0) gives all Python database drivers the same pattern.
Pass the database name as a string; keep passwords out of shared code.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Fill in the blanks (Check Your Progress 16.5, Q2): mydb = mysql.______.connect(host="localhost", ______="myusername", passwd="mypassword"), mycursor = mydb.______(), mycursor.______("CREATE DATABASE mydatabase").
Show worked answer
connector, user, cursor, execute. The full code is mydb = mysql.connector.connect(host="localhost", user="myusername", passwd="mypassword"), then mycursor = mydb.cursor() and mycursor.execute("CREATE DATABASE mydatabase").
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/data-access-using-python/connecting-python-to-mysql/ to read this page.