8

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

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())

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

[('testing',)]
[]

它应该打印:

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

怎么了?

4

1 回答 1

13

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

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())
于 2013-08-23T02:41:52.230 回答