2013-10-27 26 views
11

Sto lavorando a un programma scrabblecheatCome testare se esiste già una tabella?

Seguendo alcuni esempi, di seguito il seguente codice che utilizza SQLite per un semplice database per memorizzare le mie parole.

Tuttavia mi dice che non riesco a ricreare la tabella del database.

Come scrivere un assegno per verificare se esiste già una tabella denominata spwords, quindi saltare cercando di crearla?

L'errore:

(<class 'sqlite3.OperationalError'>, OperationalError('table spwords already exists',), None) 

Il Codice:

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() 

risposta

13

La query che stai cercando è:

SELECT name FROM sqlite_master WHERE type='table' AND name='spwords' 

Quindi, il codice dovrebbe leggere come segue:

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

Un'alternativa conveniente per SQLite 3.3+ è quello di utilizzare una query più intelligente per la creazione di tabelle invece:

CREATE TABLE IF NOT EXISTS spwords (sp_word text, word_len int, word_alpha text, word_score int) 

Dal 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

Credo che se esiste già puoi saltare l'errore e passare direttamente all'inserimento dei dati

1

Non sono un fan del rimbalzo CREATE dall'approccio al database. È necessario sapere se la tabella esiste in modo che possa verificarsi la prima inizializzazione.

Ecco la stessa risposta basata query, ma sulla base di funzioni di uso generale:

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)) 

Ora il codice superiore è

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

Hai dimenticato di passare una connessione a iStable nel tuo esempio chiamata – flaschbier

+1

Corretto . Grazie, ma dovresti sentirti libero di correggere le risposte da solo. – jdr5ca

Problemi correlati