Python 为什么';记录是否保存在sqlite3中?

Python 为什么';记录是否保存在sqlite3中?,python,database,sqlite,Python,Database,Sqlite,我第一次使用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 tex

我第一次使用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'])

这一行删除了旧表:

db.execute('drop table if exists test')
这个会创建一个新表:

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

这应该可以解释你的问题。删除这两行就可以了,但是首先要分别创建表

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

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

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

然后我该怎么办@User2864740完全相同的问题?您可以在连接()上调用
execute
@IsmailBadawi,因为它不符合DB-API,它是一个非标准的快捷方式。