Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

SQL với Python và SQLite


Hướng dẫn sử dụng SQL với Python qua module built-in sqlite3.

Kết nối database

import sqlite3
conn = sqlite3.connect("tutorialspoint.db")
cursor = conn.cursor()

Tạo bảng và chèn dữ liệu

create_table_sql = """
CREATE TABLE students (
    id INTEGER PRIMARY KEY,
    first_name VARCHAR(20),
    last_name VARCHAR(30),
    gender CHAR(1)
);
"""
cursor.execute(create_table_sql)
cursor.execute('INSERT INTO students VALUES (1, "John", "Hill", "M");')
cursor.execute('INSERT INTO students VALUES (2, "Jessy", "Hill", "F");')
cursor.execute('INSERT INTO students VALUES (3, "Antony", "Hill", "M");')
conn.commit()
conn.close()

Truy vấn dữ liệu

conn = sqlite3.connect("tutorialspoint.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students;")
students = cursor.fetchall()
print(students)
# [(1, 'John', 'Hill', 'M'), (2, 'Jessy', 'Hill', 'F'), (3, 'Antony', 'Hill', 'M')]

Kết luận

Module sqlite3 cung cấp đầy đủ CRUD, phù hợp ứng dụng nhẹ, embedded.