ALTER TABLE Sqlite: how to check if a column exists before alter the table?

前端 未结 3 2028
名媛妹妹
名媛妹妹 2021-01-02 23:59

I need to execute in python a SQL query that adds a new column, in sqlite3.

The problem is that sometimes it already exists. So previous to executing the query I ne

相关标签:
3条回答
  • 2021-01-03 00:34

    For any reason you want an explicitly way to check if a column is already present, you can find a full Python recipe below. Up to you to wrap the code in a function or improve it

    import sqlite3
    
    sqlite_db = 'my_sqlite_db.sqlite'
    col_to_test = 'my_column'
    table_to_test = 'my_table_name'
    
    con = sqlite3.connect(sqlite_db)
    check_sqlite_col_exist_query = """SELECT count(*) > 0
    FROM pragma_table_info('{}')
    WHERE name=?;""".format
    
    with con:
        q = con.execute(check_sqlite_col_exist_query(table_to_test), (col_to_test, ))
        col_exist = q.fetchone()
        col_exist = col_exist[0] > 0
        if not col_exist:
            print('"{}" column does not exist in table "{}"!'.format(col_to_test, table_to_test))
            # Do stuff here like adding your column or something else
        else:
            print('"{}" column already exist in table "{}"!'.format(col_to_test, table_to_test))
    
    0 讨论(0)
  • 2021-01-03 00:38

    IMO this

    conn = sqlite3.connect(':memory:')
    c = conn.cursor()
    try:
        c.execute('ALTER TABLE mytable ADD COLUMN newcolumn;')
    except:
        pass # handle the error
    c.close()
    

    is a better choice than constructing special case queries.

    You can wrap the above code in a AddColumn(cursor, table, column) function so you can reuse it,
    plus it'll make the code more readable.

    0 讨论(0)
  • 2021-01-03 00:53

    You can get a list of columns for a table via the following statement:

    PRAGMA table_info('table_name');
    

    More details on the pragma commands are availabel at the sqlite web site

    0 讨论(0)
提交回复
热议问题