python - 如何测试一个表是否已经存在?

标签 python sqlite

我正在开发一个拼字作弊程序

根据一些示例,我有以下代码,它使用 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)

来自documentation :

It is usually an error to attempt to create a new table in a database that already contains a table, index or view of the same name. However, if the "IF NOT EXISTS" clause is specified as part of the CREATE TABLE statement and a table or view of the same name already exists, the CREATE TABLE command simply has no effect (and no error message is returned). An error is still returned if the table cannot be created because of an existing index, even if the "IF NOT EXISTS" clause is specified.

关于python - 如何测试一个表是否已经存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622341/

相关文章:

python - 如何仅返回特定文件类型的文件?

python - 将以元组为键的字典转换为包含键和值的元组

sqlite - 如何知道sqlite文件中有什么表?

python - 绘制 pandas 数据框中的数据线,由一列中的键而不是不同的列标识

python - 如何制作Python 2轴 slider

c# - 内存数据库中的 SqlLite : CREATE TABLE does not work?

ruby-on-rails - "each"方法在开发和生产中的不同行为

android - 我们如何键入 Sqlite 查询以创建具有属性的列的顺序真的很重要吗

python - 将 Excel 的列转换为 python 中的字典

java - 在 switch 语句中使用游标 (SQLite) 移动时出现 NullPointerException