我在使用SQLite创建表格时遇到问题,只有当表格不存在时才能创建。基本上,我有一个表格,在很长一段时间内会被删除和重新创建。但是,如果在删除并重新创建之前该表格已经存在,则在第一次插入时会出现以下错误:
Traceback (most recent call last):
File "test.py", line 40, in <module>
remake()
File "test.py", line 31, in remake
insert_record(1)
File "test.py", line 36, in insert_record
c.execute(sql)
sqlite3.OperationalError: no such table: table_name
目前为止,由于某种原因,该表不存在,因此下次运行脚本时不会出现任何错误。基本上,如果我持续运行测试脚本,每隔一次运行就会发生一个错误,而我被卡住了,不知道为什么-但是我已经确定,如果不使用if not exists
创建数据库,则可以解决该问题。 但我仍然不知道最初的问题是什么,如果有人能指点我方向,我将不胜感激。下面是演示该问题的测试脚本:
import sqlite3
location = 'data'
table_name = 'table_name'
def init():
global conn
global c
conn = sqlite3.connect(location)
c = conn.cursor()
create_database()
def create_database():
sql = 'create table if not exists ' + table_name + ' (id integer)'
c.execute(sql)
conn.commit()
def create_database2():
sql = 'create table ' + table_name + '(id integer)'
c.execute(sql)
conn.commit()
def clear_database():
sql = 'drop table ' + table_name
c.execute(sql)
conn.commit()
def remake():
clear_database()
create_database() # Replacing this with create_database2() works every time
insert_record(1)
conn.commit()
def insert_record(id):
sql = 'insert into ' + table_name + ' (id) values (%d)' % (id)
c.execute(sql)
print 'Inserted ', id
init()
remake()
提前感谢你 :)