我想插入多個記錄到sqlite數據庫。這是我的測試腳本。Sqlite3插入不保留與Python的記錄
import sqlite3
from datetime import datetime
company = 'fghjk'
keyword = 'awesome'
filename = 'test.txt'
date_found = datetime.now()
conn = sqlite3.connect('C:\\sqlite\\test.db')
c = conn.cursor()
for i in range(0,4):
insert_query = "INSERT into records (company,keyword,filename,date_found) values (?,?,?,?)"
c.execute(insert_query, [company,keyword,filename,date_found])
select_query = "SELECT * FROM records"
c.execute(select_query)
res = c.fetchall()
print res
for i in res:
for b in i:
print b
當我執行上述兩次劇本,我期待有8條記錄,但它總是給人回4行。有人能夠啓發我嗎?
輸出:
1
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
2
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
3
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
4
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
這是我的表的create語句。
conn.execute('''CREATE TABLE records
# (ID INTEGER PRIMARY KEY AUTOINCREMENT,
# company TEXT NOT NULL,
# keyword INT NOT NULL,
# filename CHAR(50),
# date_found DATETIME);''')
您是否嘗試關閉腳本末尾的連接?通過用'conn:'封裝所有使用連接的代碼可以更容易地實現。我這樣運行,看到沒有問題。 –
我在腳本的末尾添加了'close()'。還是一樣的結果。你介意發佈一個答案嗎?謝謝。 @PaulRooney – essramos