7

我在 Python 中有这段代码:

conn = sqlite3.connect("people.db")
cursor = conn.cursor()

sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)
conn.commit()

sql = 'insert into people VALUES (3, "test")'
cursor.execute(sql)
conn.commit()   

sql = 'insert into people VALUES (5, "test")'
cursor.execute(sql)
conn.commit()  

print 'Printing all inserted'
cursor.execute("select * from people")
for row in cursor.fetchall():
    print row

cursor.close()
conn.close()

但似乎永远不会保存到数据库中,数据库上总是有相同的元素,就好像它没有保存任何东西一样。

另一方面,如果我尝试通过 sqlite 访问 db 文件,则会收到此错误:

Unable to open database "people.db": file is encrypted or is not a database

conn.commit我发现了其他一些可以使用的答案,conn.commit()但没有改变结果。

任何的想法?

4

4 回答 4

5

答对了 !人们!我有同样的问题。非常简单的原因之一。我正在使用 debian linux,错误是

无法打开数据库“people.db”:文件已加密或不是数据库

数据库文件与我的 python 脚本连接行位于同一目录中
conn = sqlite3.connect('./testcases.db')

我改变了这个

conn = sqlite3.connect('testcases.db')

!没有点和斜线。错误已修复。所有作品

如果有人认为它有用,欢迎您

于 2014-04-17T08:07:53.373 回答
4

这对我来说似乎没问题(每次运行时“在数据库中”都会增加):

import random, sqlite3

conn = sqlite3.connect("people.db")
cursor = conn.cursor()

sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)

for x in xrange(5):
    cursor.execute('insert into people VALUES (?, "test")', (random.randint(1, 10000),))
conn.commit()

cursor.execute("select count(*) from people")
print "In database:", cursor.fetchone()[0]
于 2012-08-04T10:11:31.397 回答
0

您可以使用 sqlite 管理员之类的工具打开数据库吗?这将证明 thedb 格式是可以的。如果我搜索该错误,则解决方案指向 sqlite 和使用的 db-driver 之间的版本问题。也许您可以检查您的版本,或者 AKX 可以发布工作组合。

问候,khz

于 2012-08-04T10:36:54.243 回答
0

您应该在进行更改后提交,即:

myDatabase.commit()
于 2020-03-05T13:58:53.340 回答