python sqlite 创建表_python sqlite“创建表如果不存在”的问题

我有一个问题,使用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()

提前致谢 :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值