這個問題在這里已經有了答案: Python SQLite 插入陳述句執行但不插入任何資料 (1 answer) 昨天關門了。
目前,我正在使用 python 設定 SQLite 資料庫。我似乎缺少一些基本的東西,因為行實際上并沒有插入磁盤上的資料庫中。
我正在瀏覽來自https://www.digitalocean.com/community/tutorials/how-to-use-the-sqlite3-module-in-python-3的數字海洋教程
這是我試圖運行的代碼:
import sqlite3
connection = sqlite3.connect("aquarium.db")
print(connection.total_changes)
cursor = connection.cursor()
# cursor.execute("CREATE TABLE fish (name TEXT, species TEXT, tank_number INTEGER)")
print(connection.total_changes)
cursor = connection.cursor()
#cursor.execute("INSERT INTO fish VALUES ('Sammy', 'shark', 1)")
#cursor.execute("INSERT INTO fish VALUES ('Jamie', 'cuttlefish', 7)")
print(connection.total_changes)
rows = cursor.execute("SELECT name, species, tank_number FROM fish").fetchall()
print(rows)
connection.close()
想象一下在第一次執行時運行包含所有行的代碼。我得到輸出:
0
0
2
[('Sammy', 'shark', 1), ('Jamie', 'cuttlefish', 7)]
我現在有一個名為 aquarium.db 的檔案,它有一個正確的模式,但這些行永遠不會存盤在磁盤上。
重新運行相同的代碼,省略我注釋掉的行,我看到檔案確實是空的:
0
0
0
[]
我在這里錯過了什么?
BR,邁克爾
uj5u.com熱心網友回復:
你需要commit()看檔案
我稍微修改了您的代碼以使其更清晰
import sqlite3
connection = sqlite3.connect("aquarium.db")
print(f"Number of changes {connection.total_changes}")
cursor = connection.cursor()
update = False
if update:
try:
cursor.execute("CREATE TABLE fish (name TEXT, species TEXT, tank_number INTEGER)")
print(f"Number of changes {connection.total_changes}")
except:
print("Couldn't create table, it probably exists.")
cursor.execute("INSERT INTO fish VALUES ('Sammy', 'shark', 1)")
cursor.execute("INSERT INTO fish VALUES ('Jamie', 'cuttlefish', 7)")
# now you need to commit your inserts
connection.commit()
print(f"Number of changes {connection.total_changes}")
rows = cursor.execute("SELECT name, species, tank_number FROM fish").fetchall()
print(rows)
connection.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537356.html
標籤:Pythonsqlite
下一篇:如何訪問查詢塊之外的變數?
