i really dont understand the following behavior:
3 Code snippets to explain
sqlconnection.h
class SqlConnection
{
public:
SqlConnection();
QSqlDatabase db;
} ;
sqlconnection.cpp
SqlConnection::SqlConnection()
{ if (!db.open()){ //no different with or without that
db = QSqlDatabase::addDatabase("QODBC");
...
}
artikelverwaltung.cpp
Artikelverwaltung::Artikelverwaltung(){
SqlConnection().db.open();
...(code to do works fine)
}
void Artikelverwaltung::on_pushButton_2_clicked()
{
SqlConnection().db.close(); // "HERE"
}
"HERE" it cycles the full Contructor of the Class again, but why it don't just close the connection? (this is the Main question about and how to fix that.)
I can't even access "db" from another Method inside the Class but outside of the Constructor, like:
sqlconnection.cpp:
void closeDB() {db.close();}
is not possible.`
What i am doing wrong?
Thank you guys
In general, you do not need to use any wrapper class to hold database connections in Qt. You should create a database connection once using QSqlDatabase::addDatabase
and open it. After that you can get a database connection anywhere by calling QSqlDatabase::database
static method. So to close the database connection you should simply call QSqlDatabase::database().close()
.