小编hip*_*tes的帖子

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(): …
Run Code Online (Sandbox Code Playgroud)

python sqlite

20
推荐指数
1
解决办法
6万
查看次数

标签 统计

python ×1

sqlite ×1