【问题标题】:SQLite not saving data between usesSQLite 在使用之间不保存数据
【发布时间】:2013-08-25 23:16:39
【问题描述】:

我做了一个模块,内容如下:

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',)]

怎么了?

【问题讨论】:

标签: python python-3.x sqlite


【解决方案1】:

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

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

【讨论】:

  • 谢谢! connection.commit() 行非常重要。你拯救了我的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多