如何將 Python 函式儲存在 Sqlite 表格中?


在以下程式碼中,我們匯入了 sqlite3 模組並建立了一個數據庫連線。我們建立了一個表,然後插入資料並從 sqlite3 資料庫中檢索資訊,最後關閉連線。

示例

#sqlitedemo.py
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})
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})
c.execute("SELECT * FROM employee WHERE last ='Doe'")
print(c.fetchone())
print(c.fetchmany(2))
conn.commit()
conn.close()

輸出

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

更新於: 2020 年 2 月 13 日

170 個瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告