微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python Sqlite3 – 数据不会永久保存

我在SQLite3和Python 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()

我做错了什么?

解决方法:

将conn.commit()调用到flush the transaction to disk.

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

注意per the docs

Connection objects can be used as context managers that automatically commit
or rollback transactions. In the event of an exception, the transaction is
rolled back; otherwise, the transaction is committed:

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

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

然后,当Python离开with语句时假设没有引发异常的错误,将自动为您提交事务.

顺便说一句,如果你使用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);''')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐