Lưu ý: Không thể lưu trực tiếp đối tượng function vào SQLite. Ví dụ này minh họa lưu dữ liệu từ đối tượng (employee) vào DB, không phải lưu hàm.
Code minh họa (lưu data, không phải function)
import sqlite3
from employee import Employee # Giả sử class Employee đã định nghĩa
conn = sqlite3.connect('employee.db')
c = conn.cursor()
c.execute('''CREATE TABLE employee(first text, last text, pay integer)''')
emp_1 = Employee('John', 'Doe', 50000)
emp_2 = Employee('Jane', 'Doe', 60000)
emp_3 = Employee('James', 'Dell', 80000)
# Insert dùng parameterized query
c.execute('''INSERT INTO employee VALUES(:first, :last, :pay)''',
{'first': emp_1.first, 'last': emp_1.last, 'pay': emp_1.pay})
c.execute('''INSERT INTO employee VALUES(:first, :last, :pay)''',
{'first': emp_2.first, 'last': emp_2.last, 'pay': emp_2.pay})
c.execute('''INSERT INTO employee VALUES(:first, :last, :pay)''',
{'first': emp_3.first, 'last': emp_3.last, 'pay': emp_3.pay})
# Query
c.execute("SELECT * FROM employee WHERE last='Doe'")
print(c.fetchone())
print(c.fetchmany(2))
conn.commit()
conn.close()
Đầu ra
('James', 'Dell', 80000)
[('James', 'Dell', 80000), ('James', 'Dell', 80000)]
Nếu muốn lưu function
Python không hỗ trợ serialize function vào DB trực tiếp. Các giải pháp:
- Lưu source code hàm dưới dạng TEXT (dùng
inspect.getsource). - Lưu tên hàm dưới dạng string, sau đó dùng
getattrđể gọi lại. - Dùng
pickle(chỉ dùng cho trusted data, không an toàn).