PDA

View Full Version : QslDatabase and default connection



frog
10th November 2009, 13:10
Hi
I m working on a wrapper class for a data base connection.
I have a member of class QSqlDatabase which is initialzed using the following call:



QSqlDatabase::addDatabase(dbDriverName,"QDB")


I connect to the data base and open the connection as following



db.setHostName("localhost");
db.setDatabaseName("dbname");
db.setUserName("dbuser");
db.setPassword("dbpassword");
db.open();

It's all fine. As you can see the connection uses a name "QDB".

I use QslQuery to do what I have to do with the data base and it fails because the connection is not opened (message from db.lastError())

At the end once I'm done, the data base connection is closed and the data base is removed using


db.close();
QSqlDatabase::removeDatabase("QDB");


While trying to query the data base QsqlQuery::exec() fails because the connection is not opened.
The call to removeDataBase complains that the connection "QDB" is still use while supposedly it failed just before (for default connection ?!)


If I do the exact same things but instead using a named connection I used the default connection QsqlQuery::exec() proceeds normally but at the end while trying to remove the database I have a warning concerning the default connection "still in use".

I put a break point in Qt src code and to my surprise QslQuery increments a ref counter of QSqlDatabase() instances. If this counter is != of 1 while calling removeDatabase() for the default connection it complains ("still in use" warning).

For a slightly more simple code example every thing works fine but the final removeDatabase complaint ("still in use").
Here is the code I used:



QSqlDatabase db= QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("dbname");
db.setUserName("dbuser");
db.setPassword("dbpasword");
db.open();

QSqlQuery query;
QString s("DROP TABLE IF EXISTS TOTO");
if(query.exec(s))
{
query.finish();
s.clear();
s.append("CREATE TABLE toto ");
s.append("(id int(8) NOT NULL PRIMARY KEY,");
s.append("name character varying(100));");
if(!query.exec(s))
cout<<"error for query :"<<s.toStdString()<<endl;
}
else
cout<<"error for query :"<<s.toStdString()<<endl;

if(db.isOpen())db.close();
db.QSqlDatabase::removeDatabase(db.connectionName( ));



So I come to my question.
What is the best way to use QslDatabase and QslQuery without getting this annoying warning message.

lyuts
10th November 2009, 13:25
The best way is to pass the database descriptor to QSqlQuery's constructor.



QSqlQuery query(db);

montuno
10th November 2009, 15:28
Unfortunately QSqlDatabase is unable to verify his state, so it's unnecessary to call close() or remove(): Look this: Qt-Bug224 (http://bugreports.qt.nokia.com/browse/QTBUG-224)