2013-10-27 85 views
11

我正在研究一个scrabblecheat程序如何测试一个表是否已经存在?

下面的一些例子我有下面的代码使用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() 

回答

13

你要找的查询是:

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.

2
conn = sqlite3.connect('sowpods.db') 
curs = conn.cursor() 
try: 
    curs.execute('''CREATE TABLE spwords(sp_word TEXT, word_len INT, word_alpha TEXT,word_score INT)''') 
    conn.commit() 
except OperationalError: 
    None 

https://docs.python.org/2/tutorial/errors.html

我相信如果它已经存在,你可以跳过错误,并直接进入插入数据

1

我不是反弹CREATE数据库方法的粉丝。您应该知道该表是否存在,以便首次进行初始化。

这里是相同的基于查询的答案,但基于通用功能:

def getTables(conn): 
    """ 
    Get a list of all tables 
    """ 
    cursor = conn.cursor() 
    cmd = "SELECT name FROM sqlite_master WHERE type='table'" 
    cursor.execute(cmd) 
    names = [row[0] for row in cursor.fetchall()] 
    return names 

def isTable(conn, nameTbl): 
    """ 
    Determine if a table exists 
    """ 
    return (nameTbl in getTables(conn)) 

现在上面的代码是

if not(isTable(conn, 'spwords')): 
    # create table and other 1st time initialization 
+0

你忘了通过在纠正了例如呼叫 – flaschbier

+1

到isTable连接。谢谢,但您应该随时自行解决问题。 – jdr5ca

相关问题