Why i cannot connect to SQLite??



  • #include "mainwindow.h"
    #include <QApplication>
    #include "login.h"
    #include <QtSql>
    #include <QSqlError>
    #include <QDebug>
    #include <QMessageBox>
    #include <QSqlDatabase>
    #include <QSqlQueryModel>

    bool connectiondb();
    bool connectiondb()
    {
    QSqlDatabase mydb=QSqlDatabase::addDatabase("QSQLITE");
    mydb.setDatabaseName("C:/Users/User/Desktop/Database Workshop/ocrms.db");
    if(!mydb.open())

        {
            QMessageBox::critical(0, QObject::tr("DATABASE CONNECTION FAILED"),mydb.lastError().text());
            return false;
        }
            else
    
    QMessageBox::information(0,"DATABASE CONNECTION SUCCESSFUL","SUCCESSFUL");
    return true;
    

    }
    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    login w;
    w.show();

    if(connectiondb())
    
        return false;
    
    return a.exec();
    

    }

    Why error occur at lasterror??No member named 'lasterror' in QSqlDatabase it says.Hope you guys can help me :) Thanks


  • Moderators

    @aana said in Why i cannot connect to SQLite??:

    No member named 'lasterror' in QSqlDatabase it says

    Who says this? The compiler? If so you have a typo - it's 'lastError()': http://doc.qt.io/qt-5/qsqldatabase.html#lastError



  • @aana

    hello I leave you an example

    if(!QSqlDatabase::isDriverAvailable("QSQLITE")){
            QMessageBox::critical(this,"Error","Driver QSQLITE unknown...");
            return  false;
        }
    else{
           QMessageBox::critical(this,"Error fatal","Error open database");
          return false;
    }
    
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("database.db");
    // Or db.setDatabaseName(ui->txtAlgo->text());
    //Or db.setDatabaseName("c:/users/user/desktop/database.db");
        if(!db.open()){
            QMessageBox::warning(this,"Error fatal","Error to open database | " + db.lastError().text());
            db.close();
            return false;
        }
    
        QSqlQuery query(db);
        query.prepare("SELECT * FROM sqlite_master WHERE type = 'table' ORDER BY name ASC");
    
    if(!query.exec()){
            QMessageBox::warning(this,"Error","Error al listar tablas de la base de datos...");
            db.close();
            return false;
        }
    
    QStringList algo;
    
        while(query.next()){
            algo.append(query.value("name").toString());
        }
        db.close();
        return true;
        
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.