为什么记录不能保存在sqlite3中?

2024-09-19 23:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是第一次使用sqlite。我以前用过Xammp。现在我看到了一个场景。每次我运行下面的代码时,记录不仅仅附加在表的末尾,而是新创建的表,因此它就像控制台一样工作。你知道吗

有人能告诉我我做错了什么吗?你知道吗

import sqlite3

db = sqlite3.connect('test.db')
db.row_factory = sqlite3.Row

db.execute('drop table if exists test')
db.execute('create table test (t1 text,i1 text)')
db.execute('insert into test (t1, i1) values (?, ?)',('xyzs','51'))
cursor = db.execute('select * from test')

for row in cursor:
    print(row['t1'],row['i1'])

Tags: 代码texttestexecutedbsqlite记录table
2条回答

首先,您需要在游标上执行命令,而不是连接本身。其次,您需要提交事务:

import sqlite3

db = sqlite3.connect('test.db')
db.row_factory = sqlite3.Row
cur = db.cursor() # getting a cursor

cur.execute('drop table if exists test')
cur.execute('create table test (t1 text,i1 text)')
db.commit() # commit the transaction, note commits are done
            # at the connection, not on the cursor

cur.execute('insert into test (t1, i1) values (?, ?)',('xyzs','51'))
db.commit()

cursor = cur.execute('select * from test')

for row in cursor:
    print(row['t1'],row['i1'])

请看一下documentation。一旦您开始使用Python中的其他数据库,这将对您有所帮助,因为它们都遵循相同的API。你知道吗

此行将删除旧表:

db.execute('drop table if exists test')

这个会创建一个新表:

db.execute('create table test (t1 text,i1 text)')

这应该能解释你的问题。删除这两行就可以了-但是首先分别创建表。你知道吗

相关问题 更多 >