MySQL Databases & SQL
Connect Python to MySQL databases. Learn to execute SQL statements, cursor controls, and fetch records.
1. Relational Databases vs. Text Files
For large applications, storing data in text files is slow. We use relational databases like MySQL. Relational databases store data in structured tables consisting of rows and columns.
2. Connecting Python to MySQL
We use the mysql.connector package. The steps to execute SQL queries in Python are:
- Establish connection: Connect to the database server using credentials (host, user, password, database).
- Allocate cursor: Create a cursor object:
mycursor = connection.cursor(). - Execute queries: Execute SQL statements using the cursor:
mycursor.execute(sql). - Commit changes: For modifying queries (like insert, update, delete), you must run
connection.commit()to save changes to the database.
💻 Python Code Examples
Example 1: Establishing Database Connection
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password"
)
print(mydb)
Description: Establishes a connection to a local MySQL server.
Example 2: Creating a Database
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE school_db")
Description: Creates a new database named school_db using the cursor.
Example 3: Creating relational tables
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="school_db"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE students (name VARCHAR(50), age INT)")
Description: Creates a student table with name and age columns.
Example 4: Inserting rows with committing
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
val = ("Peter", 22)
mycursor.execute(sql, val)
mydb.commit()
Description: Inserts a record and commits the transaction to save changes to disk.
Example 5: Selecting table records
mycursor.execute("SELECT * FROM students")
records = mycursor.fetchall()
for row in records:
print(row)
Description: Selects all records and fetches them as a list of tuples.
Example 6: Fetching a single record
mycursor.execute("SELECT * FROM students")
row = mycursor.fetchone()
print(row)
Description: Fetches only the first row matching the query.
🧠 Active Retrieval Quizzes
Answer the following 10 multiple-choice questions to test your storage strength.
Question 1: What package is used to connect Python to a MySQL database?
Question 2: What is the purpose of a database cursor object in Python?
Question 3: Why must you run connection.commit() after executing an INSERT query?
Question 4: What method fetches all results returned by a SELECT query?
Question 5: What does mycursor.fetchone() return if no more records are found?
Question 6: What parameters are required to connect Python to a database using mysql.connector.connect()?
Question 7: What data type is used to represent table rows returned by database fetch methods?
Question 8: How can you pass values dynamically into a SQL insert query to prevent SQL injection?
Question 9: What statement is executed to define a new table in SQL?
Question 10: Which cursor method closes the cursor, freeing up system resources?
🖥️ Output Prediction Challenges
Read each code snippet carefully, analyze its execution flow, and predict the exact string result written to the console.
Predict the output of the code snippet below. Type the exact output in the console.
import mysql.connector
print("Database Link Active")
Predict the output of the code snippet below. Type the exact output in the console.
row = ("Peter", 22)
name, age = row
print(name)
Predict the output of the code snippet below. Type the exact output in the console.
rows = [("Peter", 22), ("Ann", 20)]
print(len(rows))
Predict the output of the code snippet below. Type the exact output in the console.
row = ("Peter", 22)
print(type(row))
Predict the output of the code snippet below. Type the exact output in the console.
print("Transaction Committed")
🎮 Interactive Code Playground
Type your own Python code below and click "Run Code" to execute it instantly in your browser!
Console ready.
Stuck on any concept, or want to explore an edge case? Don't hesitate to ask follow-up questions to your instructor! Active questioning helps build storage strength.
📋 Progress Status
📌 Check the box above to mark this weekend's lesson complete. Your dashboard status ring will update automatically.