miércoles, 21 de septiembre de 2011

Qt SQLite 1 - Initialize and Connect

In order to connect Qt and SQLite you have to compile the SQLite drivers (in other entry I'll talk about it)

You need to include in you headers

#include <QtSql>
#include <QSqlDatabase>
 
Then in order to initialize the DB you have to give
the driver's name to addDatabse, in this case the driver's name is
"QSQLITE"
void Queries::initDB(){
    db = QSqlDatabase::addDatabase( "QSQLITE" );
    sql = QSqlQuery  (db);
}
Then to connect and query the database you have to do something like this

bool Queries::connectDB(){
    db.setDatabaseName("db.sqlite");


    if (!db.isValid()){
       QMessageBox::critical(0,"Conecction unsuccesful" 
                              ,"<b>Problems</b>:"+db.lastError().text(),
                              QMessageBox::Ok);
        exit(0);

    }
    if (!db.open()){
        QMessageBox::critical(0,"Not connected",
                              "<b>Problems</b>: The database does not exist",
                              QMessageBox::Ok);
        return false;
    }else{

        sql.clear();
        QString strSql = "CREATE  TABLE 
                          IF NOT EXISTS \"main\".\"Users\" (\"user_id\"  
                          INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , \"user\" 
                          CHAR NOT NULL , \"password\" CHAR NOT NULL )";
        sql.prepare(strSql);
        if( !sql.exec() ){
            showError(sql.lastError().text());
            exit(0);
        }else{
            strSql = "INSERT INTO Users (user,password) VALUES ('test','test')";
                    sql.prepare(strSql);
                    if( !sql.exec() )
                        showError(sql.lastError().text());
                    else{
                        if (sql.first())
                            {
                                qDebug() << sql.value(0).toString();
                            }
                    }

        }

        return true;
    }
}

No hay comentarios:

Publicar un comentario