ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

前端 未结 14 1866
青春惊慌失措
青春惊慌失措 2020-11-28 08:45

We\'ve recently had the need to add columns to a few of our existing SQLite database tables. This can be done with ALTER TABLE ADD COLUMN. Of course, if the table has alre

14条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 09:34

    Here is my solution, but in python (I tried and failed to find any post on the topic related to python):

    # modify table for legacy version which did not have leave type and leave time columns of rings3 table.
    sql = 'PRAGMA table_info(rings3)' # get table info. returns an array of columns.
    result = inquire (sql) # call homemade function to execute the inquiry
    if len(result)<= 6: # if there are not enough columns add the leave type and leave time columns
        sql = 'ALTER table rings3 ADD COLUMN leave_type varchar'
        commit(sql) # call homemade function to execute sql
        sql = 'ALTER table rings3 ADD COLUMN leave_time varchar'
        commit(sql)
    

    I used PRAGMA to get the table information. It returns a multidimensional array full of information about columns - one array per column. I count the number of arrays to get the number of columns. If there are not enough columns, then I add the columns using the ALTER TABLE command.

提交回复
热议问题