2012-03-26 64 views
0
bool MainWindow::initDb() { 
    db = QSqlDatabase::addDatabase("QSQLITE"); // defined on class header as QSqldatabase db 
    db.setDatabaseName("data.db"); 
    if (!db.open()) { 
     QMessageBox::critical(this, 
           tr("Error"), 
           tr("Could not save data. Database problem.")); 
     return false; 
    } 
    query.prepare("create table if not exists snippet (id int primary key, title varchar(255) not null, tags varchar(255), snippet text)"); 
    if (!query.exec()) { // error 
     QMessageBox::critical(this, 
           tr("Database error"), 
           tr("Could not setup database")); 
     qDebug() << "Database error : " << query.lastError(); 
     return false; 
    } 
    query.clear(); 
    return true; 
} 

數據庫它顯示數據庫錯誤消息框,並在控制檯下面。Qt的查詢執行錯誤

Database error : QSqlError(-1, "Driver not loaded", "Driver not loaded") 
+0

這是什麼平臺?你有安裝sqlite和sqlite qt插件嗎? – 2012-03-26 06:00:18

+0

Linux ubuntu 11.10,安裝了SQLIte。如果我使用查詢作爲本地對象,即使工作正常。只是因爲當**查詢**在類屬性問題出現時。 – Dewsworld 2012-03-26 07:03:26

+1

如果它是類成員,則使用默認構造函數:http://qt-project.org/doc/qt-4.8/qsqlquery.html#QSqlQuery-2。嘗試實例化傳遞正確的數據庫。 – 2012-03-26 07:06:27

回答

1

我得到了部分解決方案。使查詢作爲本地對象與傳遞db它的構造函數解決問題。 Like

QSqlQuery query(db);