这是我的小数据库:
import sqlite3def 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,1 )");def printAll(cursor): cursor = conn.execute("SELECT ID,filename,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 onceinsert()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,Voting REAL);''')总结
以上是内存溢出为你收集整理的Python Sqlite3 – 数据不会永久保存全部内容,希望文章能够帮你解决Python Sqlite3 – 数据不会永久保存所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)