如何测试表是否已存在?

Leo*_*ban 11 python sqlite

我正在制作一个scrabblecheat计划

下面是一些例子,我在下面的代码中使用SQLite作为一个简单的数据库来存储我的单词.

但它告诉我我无法重新创建数据库表.

如何在检查中是否已经有一个已命名的表spwords,然后跳过尝试创建它?

错误:

(<class 'sqlite3.OperationalError'>, OperationalError('table spwords already exists',), None)
Run Code Online (Sandbox Code Playgroud)

代码:

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

Bar*_*zKP 15

您正在寻找的查询是:

SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'
Run Code Online (Sandbox Code Playgroud)

因此,代码应如下所示:

tb_exists = "SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'"
if not conn.execute(tb_exists).fetchone():
    conn.execute(tb_create)
Run Code Online (Sandbox Code Playgroud)

SQLite 3.3+的一个方便的替代方法是使用更智能的查询来代替创建表:

CREATE TABLE IF NOT EXISTS spwords (sp_word text, word_len int, word_alpha text, word_score int)
Run Code Online (Sandbox Code Playgroud)

文档:

尝试在已包含同名的表,索引或视图的数据库中创建新表通常是错误的.但是,如果将"IF NOT EXISTS"子句指定为CREATE TABLE语句的一部分并且已存在同名的表或视图,则CREATE TABLE命令将无效(并且不会返回任何错误消息).如果由于现有索引而无法创建表,则仍会返回错误,即使指定了"IF NOT EXISTS"子句也是如此.