Python,Sqlite 未将结果保存在文件中

Mc-*_*Mc- 7 python database sqlite

我在 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()
Run Code Online (Sandbox Code Playgroud)

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

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

Unable to open database "people.db": file is encrypted or is not a database
Run Code Online (Sandbox Code Playgroud)

我在其他一些答案中找到了使用conn.commit而不是conn.commit()但并没有改变结果。

任何的想法?

小智 6

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

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

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

我改变了这个

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

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

如果有人觉得有用,不客气


AKX*_*AKX 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]
Run Code Online (Sandbox Code Playgroud)