ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

前端 未结 14 1745
青春惊慌失措
青春惊慌失措 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:27

    You can alternatively use the CASE-WHEN TSQL statement in combination with pragma_table_info to know if a column exists:

    select case(CNT) 
        WHEN 0 then printf('not found')
        WHEN 1 then printf('found')
        END
    FROM (SELECT COUNT(*) AS CNT FROM pragma_table_info('myTableName') WHERE name='columnToCheck') 
    
    0 讨论(0)
  • 2020-11-28 09:29

    In case you're having this problem in flex/adobe air and find yourself here first, i've found a solution, and have posted it on a related question: ADD COLUMN to sqlite db IF NOT EXISTS - flex/air sqlite?

    My comment here: https://stackoverflow.com/a/24928437/2678219

    0 讨论(0)
  • 2020-11-28 09:31

    If you are doing this in a DB upgrade statement, perhaps the simplest way is to just catch the exception thrown if you are attempting to add a field that may already exist.

    try {
       db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN foo TEXT default null");
    } catch (SQLiteException ex) {
       Log.w(TAG, "Altering " + TABLE_NAME + ": " + ex.getMessage());
    }
    
    0 讨论(0)
  • 2020-11-28 09:33

    I took the answer above in C#/.Net, and rewrote it for Qt/C++, not to much changed, but I wanted to leave it here for anyone in the future looking for a C++'ish' answer.

        bool MainWindow::isColumnExisting(QString &table, QString &columnName){
    
        QSqlQuery q;
    
        try {
            if(q.exec("PRAGMA table_info("+ table +")"))
                while (q.next()) {
                    QString name = q.value("name").toString();     
                    if (columnName.toLower() == name.toLower())
                        return true;
                }
    
        } catch(exception){
            return false;
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-11-28 09:34

    threre is a method of PRAGMA is table_info(table_name), it returns all the information of table.

    Here is implementation how to use it for check column exists or not,

        public boolean isColumnExists (String table, String column) {
             boolean isExists = false
             Cursor cursor;
             try {           
                cursor = db.rawQuery("PRAGMA table_info("+ table +")", null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        if (column.equalsIgnoreCase(name)) {
                            isExists = true;
                            break;
                        }
                    }
                }
    
             } finally {
                if (cursor != null && !cursor.isClose()) 
                   cursor.close();
             }
             return isExists;
        }
    

    You can also use this query without using loop,

    cursor = db.rawQuery("PRAGMA table_info("+ table +") where name = " + column, null);
    
    0 讨论(0)
  • 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.

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