Giới thiệu
SQLite DB ghi trong 1 file duy nhất → dễ dùng, truy cập, thao tác, phân tích. Python có sẵn package sqlite3.
Bắt đầu
Python đã cài sẵn sqlite3, chỉ cần import.
import sqlite3
Tạo database
database = sqlite3.connect("Student_records.db")
print("Kết nối thành công!")
database.close()
File Student_records.db xuất hiện trong working directory.
Thêm cột (attributes)
database = sqlite3.connect("Student_records.db")
print("Kết nối thành công!")
database.execute("""CREATE TABLE Scores(
ID INT PRIMARY KEY NOT NULL,
NAMES TEXT NOT NULL,
MARKS TEXT NOT NULL,
GRADES NOT NULL)""")
print("Các cột đã tạo trong Database")
database.close()
NOT NULL = bắt buộc nhập, PRIMARY KEY = duy nhất (không trùng ID).
Chèn bản ghi
connection = sqlite3.connect("Student_records.db")
print("Kết nối thành công!")
cursor = connection.cursor()
cursor.execute("""INSERT INTO Scores(ID,NAMES,MARKS,GRADES) VALUES(?,?,?,?)""", (1, "Vijay", 93, "A"))
connection.commit()
connection.close()
cursor = con trỏ duyệt bản ghi. commit() lưu thay đổi. Thêm bản ghi khác bằng thêm cursor.execute.
Tip: Dùng DB Browser (free, open-source) xem DB qua GUI.
Ví dụ hoàn chỉnh
import sqlite3
connection = sqlite3.connect("Student_records.db")
print("Kết nối thành công!")
cursor = connection.cursor()
cursor.execute("""INSERT INTO Scores (ID,NAMES,MARKS,GRADES) VALUES(?,?,?,?)""", (1, "Vijay", 93, "A"))
cursor.execute("""INSERT INTO Scores (ID,NAMES,MARKS,GRADES) VALUES(?,?,?,?)""", (2, "Tony", 86, "B"))
cursor.execute("""INSERT INTO Scores (ID,NAMES,MARKS,GRADES) VALUES(?,?,?,?)""", (3, "Stark", 100, "A"))
cursor.execute("""INSERT INTO Scores (ID,NAMES,MARKS,GRADES) VALUES(?,?,?,?)""", (4, "Steve", 63, "C"))
print("Đã thêm bản ghi")
connection.commit()
connection.close()
input("Nhấn Enter để thoát")
Kết luận
Đã tạo DB, bảng, cột, chèn dữ liệu. SQLite còn hỗ trợ: xem, cập nhật, xóa, sắp xếp, phân tích... Xem tài liệu.