【问题标题】:Python Sqlite3 - Data is not saved permanentlyPython Sqlite3 - 数据未永久保存
【发布时间】:2021-09-14 21:45:57
【问题描述】:

我在 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


    【解决方案1】:

    致电conn.commit()flush the transaction to disk

    当程序退出时,最后一个未完成的事务回滚到最后一次提交。 (或者,更准确地说,the rollback is done by the next program to open the database。)因此,如果从未调用过commit,则数据库不会发生任何变化。

    注意per the docs:

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

    因此,如果您使用这样的 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);''')
    

    【讨论】:

    • O_o 这太快了!感谢您的回答和链接!
    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 2011-05-18
    相关资源
    最近更新 更多