简体   繁体   中英

SQLite - Check table format on CREATE and drop if needed

Say I need a table that has to have two columns (A TEXT, B TEXT). Every time before I run a program, I want to check if the table exists, and create it if it doesn't. Now say that the table with that name exists already, but has only one column (A TEXT), or maybe (A INT, B INT)

So in general, different columns. How do I check that on CREATE query? And if there's a conflict back it up somewhere and drop, then create a new correct table. If there's no conflict - don't do anything.

I am working in Python, using sqlite3 by the way. Database is stored locally for now and program is distributed to multiple people, that's why I need to check the database.

Currently I have

con = sqlite3.connect(path)
with con:
  cur = con.cursor()
  cur.execute('CREATE TABLE IF NOT EXISTS table (A TEXT, B TEXT);')

You can use the pragma table_info in order to get information about the table, and use the result to check your columns:

def validate(connection):
    cursor = connection.cursor()
    cursor.execute('PRAGMA table_info(table)')
    columns = cursor.fetchall()
    cursor.close()
    return (len(columns) == 2
            and columns[0][1:3] == ('A', 'TEXT')
            and columns[1][1:3] == ('B', 'TEXT'))

So if validate returns False you can rename the table and create the new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM