Python错误集锦:sqlite3建表时提示:sqlite3.OperationalError: table table_juzicode already exists

原文链接:http://www.juzicode.com/archives/3940

错误提示:

sqlite3建表时提示:sqlite3.OperationalError: table table_juzicode already exists

#juzicode.com/vx:桔子code
import sqlite3
db_name = 'test.db'
table_name = 'table_juzicode'
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
sql = '''CREATE TABLE '''+table_name +''' (
     _id INTEGER PRIMARY KEY AUTOINCREMENT,
     name TEXT,      
     price FLOAT,
     weight FLOAT
     )'''
cursor.execute(sql)     
==========运行结果:
--------------------------------------------------------------------------- 
OperationalError                          
Traceback (most recent call last) <ipython-input-7-0d0e9d4b9ba1> in <module>
      11     weight FLOAT
      12     )''' 
---> 13 cursor.execute(sql) 
OperationalError: table table_juzicode already exists

 

错误原因:

1、sqlite3使用”CREATE TABLE”建表时,如果数据库文件中已经存在同名的表,会抛异常提示Operation Error。

 

解决方法:

1、在建表前先检查是否存在该表,如果存在则不建表,不存在时才建表。

 #juzicode.com/vx:桔子code
 import sqlite3
 db_name = 'test.db'
 table_name = 'table_juzicode'
 conn = sqlite3.connect(db_name)
 cursor = conn.cursor()
 sql = '''SELECT tbl_name FROM sqlite_master WHERE type = 'table' '''
 cursor.execute(sql)
 values = cursor.fetchall()
 tables = []
 for v in values:
     tables.append(v[0])
 #如果表名不存在,建表
 if table_name not in tables:
     sql = '''CREATE TABLE '''+table_name +''' (
         _id INTEGER PRIMARY KEY AUTOINCREMENT,
         name TEXT,      
         price FLOAT,
         weiht FLOAT
         )'''
     cursor.execute(sql)
     print(table_name + ' 创建成功')
 else:
     print(table_name + ' 已经存在')
==========运行结果:
table_juzicode 创建成功

==========运行结果(第2次):
table_juzicode 已经存在

 

扩展内容:

  1. Python进阶教程m12–sqlite3模块
posted @ 2021-04-03 08:03  桔子code  阅读(525)  评论(0编辑  收藏  举报