Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเก็บข้อมูลจากฟังก์ชัน Python ลงตาราง SQLite

ตัวอย่างใช้ sqlite3 module สร้างตาราง เพิ่มข้อมูล และ query ข้อมูล (ไม่ได้เก็บฟังก์ชันโดยตรง แต่เก็บข้อมูลที่ฟังก์ชันสร้าง/คืนค่า)

ตัวอย่าง

import sqlite3
from employee import employee

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)

c.execute('''INSERT INTO employee VALUES(:first, :last, :pay)''',
          {'first': emp_1.first, 'last': emp_1.last, 'pay': emp_1.pay})
# ... insert emp_2, emp_3

c.execute("SELECT * FROM employee WHERE last='Doe'")
print(c.fetchone())
print(c.fetchmany(2))

conn.commit()
conn.close()

ผลลัพธ์

('James', 'Dell', 80000)
[('James', 'Dell', 80000), ('James', 'Dell', 80000)]

หมายเหตุ: ตัวอย่างนี้เก็บข้อมูล object ไม่ใช่ฟังก์ชันเอง