如何测试表是否已经存在?
我正在做一个拼字游戏程序
在下面的示例中,我下面的代码使用SQLite作为简单数据库来存储我的单词。
但是,它告诉我无法重新创建数据库表。
如何检查是否已经存在一个名为的表spwords
,然后跳过尝试创建表的操作?
错误:
(<class 'sqlite3.OperationalError'>, OperationalError('table spwords already exists',), None)
编码:
def load_db(data_list):
# create database/connection string/table
conn = sqlite.connect("sowpods.db")
#cursor = conn.cursor()
# create a table
tb_create = """CREATE TABLE spwords
(sp_word text, word_len int, word_alpha text, word_score int)
"""
conn.execute(tb_create) # <- error happens here
conn.commit()
# Fill the table
conn.executemany("insert into spwords(sp_word, word_len, word_alpha, word_score) values (?,?,?,?)", data_list)
conn.commit()
# Print the table contents
for row in conn.execute("select sp_word, word_len, word_alpha, word_score from spwords"):
print (row)
if conn:
conn.close()
-
您要查找的查询是:
SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'
因此,代码应如下所示:
tb_exists = "SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'" if not conn.execute(tb_exists).fetchone(): conn.execute(tb_create)
SQLite 3.3+的一个方便的替代方法是使用更智能的查询来创建表:
CREATE TABLE IF NOT EXISTS spwords (sp_word text, word_len int, word_alpha text, word_score int)
从文档中:
试图在已经包含相同名称的表,索引或视图的数据库中创建新表通常是错误的。但是,如果将“ IF NOT EXISTS”子句指定为CREATE
TABLE语句的一部分,并且已经存在相同名称的表或视图,则CREATE
TABLE命令将完全无效(并且不会返回错误消息)。如果由于存在索引而无法创建表,即使指定了“ IF NOT EXISTS”子句,仍然会返回错误。