Python Sqlite3-数据不会永久保存



我使用SQLite3Python 3

这是我的小数据库:

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()将事务刷新到磁盘。

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

最新更新