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

Sử dụng SQL với Python

Trong hướng dẫn này, chúng ta học cách dùng SQL với Python qua database SQLite. Python có module built-in sqlite3.

Các bước kết nối:

  • Import sqlite3.
  • Tạo kết nối: sqlite3.connect(db_name) - tạo file nếu chưa có.
  • Lấy cursor: conn.cursor() - trung gian thực thi SQL.

Ví dụ kết nối

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

Tạo bảng, chèn dữ liệu, commit, đóng kết nối:

Ví dụ

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

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:

Ví dụ

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

cursor.execute("SELECT * FROM students;")
students = cursor.fetchall()
print(students)

Kết quả

[(1, 'John', 'Hill', 'M'), (2, 'Jessy', 'Hill', 'F'), (3, 'Antony', 'Hill', 'M')]

Kết luận

sqlite3 cho phép làm việc SQLite từ Python: connect, cursor, execute, commit, fetchall. Hãy bình luận nếu có thắc mắc.