initialize connection database in .h
-
Hello,
I'm tring to externalize my database connection.
This code works :
mainwindow.cppdatabase.setHostName("localhost"); database.setDatabaseName("base"); database.setUserName("base"); database.setPassword("base"); QString identifiant = ui->identifiant->text(); QString motdepasse = ui->motdepasse->text(); QSqlQuery qry; qry.prepare("INSERT INTO utilisateur (identifiant, motdepasse)" "VALUES (:identifiant,:motdepasse)"); qry.bindValue(":identifiant", identifiant); qry.bindValue(":motdepasse", motdepasse); if(qry.exec()) { QMessageBox::information(this,"Inséré","Vous êtes bien inscrits"); } else{ QMessageBox::information(this,"Pas inséré","Les données ne se sont pas bien insérées"); } }
Now i want to put my connection in another file and call it.
So i changed to this :
mainwindow.cpp#include "initdb.h" #include <QtSql> if (!QSqlDatabase::drivers().contains("QMYSQL")) QMessageBox::critical( this, "Unable to load database", "This demo needs the QMYSQL driver" ); // Initialize the database: QSqlError err = initDb(); if (err.type() != QSqlError::NoError) { showError(err); return; } QString identifiant = ui->identifiant->text(); QString motdepasse = ui->motdepasse->text(); QSqlQuery qry; qry.prepare("INSERT INTO utilisateur (identifiant, motdepasse)" "VALUES (:identifiant,:motdepasse)"); qry.bindValue(":identifiant", identifiant); qry.bindValue(":motdepasse", motdepasse); if(qry.exec()) { QMessageBox::information(this,"Inséré","Vous êtes bien inscrits"); } else{ QMessageBox::information(this,"Pas inséré","Les données ne se sont pas bien insérées"); } }
initdb.h
#ifndef INITDB_H #define INITDB_H #include <QtSql> QSqlError initDb() { QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL"); database.setHostName("base"); database.setDatabaseName("base"); database.setUserName("base"); database.setPassword("base"); if (!database.open()) return database.lastError(); return QSqlError(); } #endif // INITDB_H
But the insertion doesn't work. No error, but it seems to not be initalize.
Thanks
-
@Cervo2paille said in initialize connection database in .h:
QSqlQuery qry;
You need to tell the query which database to use as you do not use the default one:
QSqlQuery qry(QSqlDatabase::database("base"));
-
@jsulm said in initialize connection database in .h:
You need to tell the query which database to use as you do not use the default one:
? Where does code set a connection name? I can only see
setDatabaseName("base")
, that is database not connection name?@Cervo2paille
I do not know what you are trying to do. Why are you trying to write database opening code in a.h
file? And you only want to open the database once in any circumstance. After that you can access it viastatic QSqlDatabase QSqlDatabase::database()
, if you need it all. If you leave it as you have as the default connection you won't need it anyway.