python sqlite"如果不存在则创建表"问题

hip*_*tes 20 python sqlite

我有一个问题,使用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
Run Code Online (Sandbox Code Playgroud)

此时表不存在(由于某种原因),因此下次运行脚本时不会发生错误.基本上,如果我继续运行测试脚本,恰好每一次运行都会导致错误,我很难过为什么 - 但我已经确定创建数据库而不使用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()
Run Code Online (Sandbox Code Playgroud)

提前致谢 :)

Wan*_*wei 33

我可以使用以下简化脚本复制该问题:

import sqlite3

location = 'data'
table_name = 'table_name'

conn = sqlite3.connect(location)
c = conn.cursor()

sql = 'create table if not exists ' + table_name + ' (id integer)'
c.execute(sql)

sql = 'drop table ' + table_name
c.execute(sql)

sql = 'create table if not exists ' + table_name + ' (id integer)'
c.execute(sql)

sql = 'insert into ' + table_name + ' (id) values (%d)' % (1)
c.execute(sql)
conn.commit()
Run Code Online (Sandbox Code Playgroud)

要解决此问题,您必须在创建或删除表后关闭并重新连接到数据库,即在其间添加以下代码:

c.close()
conn.close()
conn = sqlite3.connect(location)
c = conn.cursor()
Run Code Online (Sandbox Code Playgroud)

不知道原因是什么.


更新2018年10月16日

从2.7.12开始,此问题不再可重现,但我没有在更改日志中看到它.如果您仍然看到它,请尝试先更新您的python版本.