Python SQLite3: Module chuẩn kết nối SQLite
SQLite là database nhúng, serverless, file đơn (.sqlite3). Python thư viện chuẩn có sẵn module sqlite3 (DB-API 2.0, PEP 249).
Kết nối database
import sqlite3
# File trên đĩa (tạo mới nếu chưa có)
conn = sqlite3.connect('mydb.sqlite3')
# Database trong RAM (tạm, mất khi đóng)
conn = sqlite3.connect(':memory:')
Đối tượng Connection - Các phương thức chính
cursor(): Tạo con trỏ thực thi SQL.commit(): Cam kết transaction.rollback(): Hoàn tác transaction.execute(sql): Thực thi SQL (tạo cursor ngầm).executemany(sql, seq_params): Thực thi hàng loạt.iterdump(): Xuất dump SQL text.backup(dest_conn): Sao chép DB (online backup).create_function(),create_aggregate(): Đăng ký hàm Python dùng trong SQL.
Đối tượng Cursor - Thao tác dữ liệu
cur = conn.cursor()
-- Tạo bảng
cur.execute("""CREATE TABLE guests (
ID INTEGER PRIMARY KEY,
name TEXT(20) NOT NULL,
address TEXT(40),
city TEXT(20)
);""")
-- Chèn 1 dòng
cur.execute("INSERT INTO guests VALUES(1,'RAJU','ABIDS','HYDERABAD')")
-- Chèn nhiều dòng (parameterized query - an toàn SQL injection)
addresses = [(2,'KISHAN','TILAK ROAD','PUNE'), (3,'LATA','GAANDHI NAGAR','AURANGABAD')]
cur.executemany('INSERT INTO guests VALUES (:ID, :NAME, :ADD, :CITY)', addresses)
conn.commit()
Truy vấn dữ liệu
-- fetchone(): lặp từng dòng
cur.execute("SELECT * FROM guests")
while True:
row = cur.fetchone()
if row is None: break
print(row)
-- fetchall(): lấy tất cả thành list
cur.execute("SELECT * FROM guests")
rows = cur.fetchall()
for row in rows:
print(row)
Ánh xạ kiểu dữ liệu SQLite ↔ Python
| Python | SQLite |
|---|---|
| None | NULL |
| int | INTEGER |
| float | REAL |
| str | TEXT |
| bytes | BLOB |
Xử lý ngoại lệ (Exceptions)
DatabaseError: Lỗi liên quan database.IntegrityError: Vi phạm ràng buộc (FK, UNIQUE...).ProgrammingError: Lỗi cú pháp, bảng không tồn tại, sai tham số.OperationalError: Lỗi vận hành (disk full, lock, timeout).NotSupportedError: Tính năng không hỗ trợ.
try:
conn.execute("INSERT ...")
conn.commit()
except sqlite3.IntegrityError as e:
print("Trùng khóa:", e)
conn.rollback()
except sqlite3.OperationalError as e:
print("Lỗi vận hành:", e)
conn.rollback()
Best Practices
- Luôn dùng parameterized query (placeholder
?hoặc:name) tránh SQL Injection. - Dùng
with conn:context manager tự commit/rollback (Python 3.4+). - Đóng connection:
conn.close()hoặc dùngwith. - Với đa luồng: Mỗi thread tự tạo connection riêng (sqlite3 không thread-safe cho connection chia sẻ).