SQLite 在使用之间不保存数据 [英] SQLite not saving data between uses

查看:136
本文介绍了SQLite 在使用之间不保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个包含以下内容的模块:

I made a module with the following contents:

import sqlite3 as sq
connection = sq.connect("test.db")
cursor = connection.cursor()
cursor.execute("DROP TABLE IF EXISTS test")
cursor.execute("CREATE TABLE test (st TEXT)")
cursor.execute("INSERT INTO test VALUES ('testing')")
cursor.execute("SELECT * FROM test")
print(cursor.fetchall())
cursor.close()
connection.close()
connection2 = sq.connect("test.db")
cursor2 = connection2.cursor()
cursor2.execute("SELECT * FROM test")
print(cursor2.fetchall())

但是当我运行它时,它打印了以下内容:

But when I ran it, it printed the following:

[('testing',)]
[]

它应该打印:

[('testing',)]
[('testing',)]

怎么了?

推荐答案

您没有将更改提交到数据库中.当您放弃连接时,事务将被回滚.这有效

You did not commit your changes into the DB. When you discard the connection, the transaction will be rolled back. This works

import sqlite3 as sq
connection = sq.connect("test.db")
cursor = connection.cursor()
cursor.execute("DROP TABLE IF EXISTS test")
cursor.execute("CREATE TABLE test (st TEXT)")
cursor.execute("INSERT INTO test VALUES ('testing')")
connection.commit() # !!!

cursor.execute("SELECT * FROM test")
print(cursor.fetchall())
cursor.close()
connection.close()  # rolls back changes without .commit()

connection2 = sq.connect("test.db")
cursor2 = connection2.cursor()
cursor2.execute("SELECT * FROM test")
print(cursor2.fetchall())

这篇关于SQLite 在使用之间不保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆