Python
Module 13: Python Database ProgrammingBeginner22 min read

Connecting to MySQL & SQLite

Connect to relational databases, execute parameterized queries, and commit transactions.

Key Takeaways & Core Concepts
  • FROM users")

Connecting to MySQL & SQLite

### Python Database Connectivity

Python connects to relational databases like MySQL, PostgreSQL, and SQLite using the standard Python DB-API 2.0 interface.

#### 1. SQLite (Built-in) SQLite requires no server installation and stores data in a single local file:

PYTHON Code Example
1import sqlite3
2
3# Connect to in-memory database
4conn = sqlite3.connect(":memory:")
5cursor = conn.cursor()
6
7# Create table
8cursor.execute("""
9 CREATE TABLE users (
10 id INTEGER PRIMARY KEY,
11 username TEXT NOT NULL,
12 role TEXT NOT NULL
13 )
14""")
15
16# Parameterized INSERT (prevents SQL Injection!)
17cursor.execute("INSERT INTO users (username, role) VALUES (?, ?)", ("admin", "Superuser"))
18conn.commit()
19
20cursor.execute("SELECT * FROM users")
21print(cursor.fetchall())
22conn.close()
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
22 lines

#### Security Best Practice: Never Concatenate SQL Strings! Always use parameterized placeholders (? in SQLite, %s in MySQL/PostgreSQL) to defend against SQL Injection vulnerabilities.

Parameterized SQLite Operations
1import sqlite3
2
3conn = sqlite3.connect(":memory:")
4c = conn.cursor()
5c.execute("CREATE TABLE products (name TEXT, price REAL)")
6c.execute("INSERT INTO products VALUES (?, ?)", ("Python Book", 499.0))
7conn.commit()
8
9c.execute("SELECT name, price FROM products WHERE price < ?", (1000,))
10rows = c.fetchall()
11print("Products:", rows)
12conn.close()
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines
Note: Parameter tuples prevent SQL injection by treating input strictly as data.
Practice & AssessmentPython Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)