我正在开发一个拼字作弊程序
根据一些示例,我有以下代码,它使用 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/