Python and SQL Connectivity
Connecting Python with SQL databases allows you to interact with data programmatically. This page demonstrates the steps for Python and SQL connectivity, focusing on MySQL (popular for larger systems) and SQLite (built-in).
Connecting to MySQL
For larger databases, MySQL is widely used. Use the mysql-connector-python
library for connectivity.
Steps to Connect
- Install the MySQL connector library:
pip install mysql-connector-python
- Import the library and establish a connection.
- Execute queries using a cursor object.
- Commit changes and close the connection.
Example: MySQL Connection
import mysql.connector
# Connect to MySQL server
connection = mysql.connector.connect(
host="localhost",
user="root", # Replace with your username
password="password", # Replace with your password
database="test_db" # Replace with your database name
)
cursor = connection.cursor()
# Create a table
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
salary FLOAT
)
""")
print("Table created successfully!")
# Insert data
cursor.execute("INSERT INTO employees (name, salary) VALUES (%s, %s)", ("John Doe", 50000))
cursor.execute("INSERT INTO employees (name, salary) VALUES (%s, %s)", ("Jane Smith", 60000))
connection.commit() # Save changes
# Fetch data
cursor.execute("SELECT * FROM employees")
rows = cursor.fetchall()
print("Employees in database:", rows)
# Close the connection
connection.close()
Connecting to SQLite
SQLite is a lightweight database built into Python. It’s perfect for small applications or learning.
Steps to Connect
- Import the
sqlite3
module. - Establish a connection to the database file (
.db
). - Create a cursor object to execute SQL commands.
- Execute queries and fetch results.
- Close the connection.
Example: SQLite Connection
import sqlite3
# Connect to SQLite database (creates file if it doesn't exist)
connection = sqlite3.connect("example.db")
cursor = connection.cursor()
# Create a table
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
""")
print("Table created successfully!")
# Insert data
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 25))
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Bob", 30))
connection.commit() # Save changes
# Fetch data
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
print("Users in database:", rows)
# Close the connection
connection.close()
Key Differences Between MySQL and SQLite
Feature | MySQL | SQLite |
---|---|---|
Setup | Requires server setup | Built-in, no setup needed |
Performance | Better for large apps | Lightweight, for small apps |
Scalability | Supports distributed data | Single file |
Security | Advanced options | Limited |
Best Practices for Python-SQL Connectivity
- Use Parameterized Queries: Prevent SQL injection by using placeholders (
?
for SQLite,%s
for MySQL).cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 25))
- Handle Exceptions: Always wrap your database operations in try-except blocks.
try: # Database operations except Exception as e: print("Error:", e)
- Close Connections: Always close the connection to avoid resource leaks.
connection.close()
Try It Yourself
Problem 1: Create a Database and Table (MySQL)
Task: Write a program to create a database named school
and a table students
with columns id
, name
, and class
.
Show Solution
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password"
)
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS school")
cursor.execute("""
CREATE TABLE IF NOT EXISTS school.students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
class INT
)
""")
print("Table 'students' created in 'school' database")
connection.close()
Problem 2: Navigate SQLite Database
Task: Write a program to connect to a SQLite database and fetch all rows from a table products
.
Show Solution
import sqlite3
connection = sqlite3.connect("shop.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM products")
rows = cursor.fetchall()
for row in rows:
print(row)
connection.close()
Python’s flexibility with databases makes it a powerful tool for backend development and data manipulation.