我有一个问题,使用sqlite创建一个表,只有当它不存在.基本上,我有一张桌子,我在很长一段时间内掉下来,重新制作一次.但是,如果该表已经存在(在我丢弃并重新制作之前),那么当第一次尝试插入时,我会收到以下错误:
Traceback (most recent call last):
File "test.py", line 40, in
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
此时,表不存在(由于某种原因),所以下次运行脚本时不会发生错误.基本上,如果我继续运行测试脚本,那么每一个其他的运行都会导致一个错误,而且我被困在为什么 – 但我已经确定创建数据库而不使用如果不存在则修复了问题.我仍然不知道原来的问题是什么,如果有人能指出我正确的方向,我将不胜感激.测试脚本演示下面的问题:
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()
提前致谢 :)