Python Sqlite3 - 数据不会永久保存

问题描述 投票:0回答:2

我在 SQLite3Python 3 上做错了什么。也许我误解了 SQLite 数据库的概念,但我希望即使关闭应用程序后,数据也会存储在数据库中?当我插入数据并重新打开应用程序时,插入消失了,数据库为空。

这是我的小数据库:

import sqlite3

def createTable():
    conn.execute('''CREATE TABLE VideoFile
           (ID INTEGER PRIMARY KEY NULL,
           FileName           TEXT    NOT NULL,
           FilePath           TEXT    NOT NULL,
           numOfFrames            INT     NOT NULL,
           FPS            INT     NOT NULL,
           Tags           TEXT    NOT NULL,
           Voting         REAL);''')


def insert():
    conn.execute("INSERT INTO VideoFile (Filename, FilePath, numOfFrames,FPS, Tags, Voting) \
                              VALUES ('ARCAM_0010_100', 'Categories/Dirt/Small', 2340, 50, 'Bock', 1 )");
    conn.execute("INSERT INTO VideoFile (Filename, FilePath, numOfFrames,FPS, Tags, Voting) \
                              VALUES ('ARCAM_0010_100', 'Categories/Dirt/Small', 2340, 50, 'Bock', 1 )");

def printAll(cursor):   
    cursor = conn.execute("SELECT ID, FileName, FilePath, numOfFrames  from VideoFile")
    for row in cursor:
       print("ID = ", row[0])
       print("FileName = ", row[1])
       print("FilePath = ", row[2])
       print("numOfFrames = ", row[3], "\n")

    print("Operation done successfully")
    conn.close()


conn = sqlite3.connect('AssetBrowser.db')
createTable()

#comment out after executing once
insert()
printAll()

我哪里做错了?

python sqlite
2个回答
24
投票

调用

conn.commit()
将交易刷新到磁盘

当程序退出时,最后一个未完成的事务将回滚到最后一次提交。 (或者,更准确地说,回滚是由下一个打开数据库的程序完成的。)因此,如果从未调用

commit
,则数据库不会发生任何更改。

请注意根据文档

连接对象可以用作自动提交的上下文管理器 或回滚事务。如果出现异常,则交易 回滚;否则,事务将被提交:

因此,如果你使用这样的with语句:

with sqlite3.connect('AssetBrowser.db') as conn:
    createTable()
    insert()
    printAll()

然后,当 Python 离开

with-statement
时,假设没有引发异常的错误,事务将自动为您提交。


顺便说一句,如果您使用

CREATE TABLE IF NOT EXISTS
,那么 仅当该表尚不存在时才会创建该表。这样做,调用一次后就不必注释掉
createTable

def createTable():
    conn.execute('''CREATE TABLE IF NOT EXISTS VideoFile
           (ID INTEGER PRIMARY KEY NULL,
           FileName           TEXT    NOT NULL,
           FilePath           TEXT    NOT NULL,
           numOfFrames            INT     NOT NULL,
           FPS            INT     NOT NULL,
           Tags           TEXT    NOT NULL,
           Voting         REAL);''')

0
投票

如果您想避免必须记住在写入数据库的代码的每个部分中调用

commit()
,您可以在自动提交模式下打开连接,如下所示:
sqlite3.connect(autocommit=True)

但是,我仅建议您执行的每次插入或更新不会使数据模型陷入不一致状态时执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.