ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

前端 未结 14 1871
青春惊慌失措
青春惊慌失措 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条回答
  •  萌比男神i
    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;
    }
    

提交回复
热议问题