PDA

View Full Version : Error using QSqlDatabase QSqlDatabase::addDatabase ( QSqlDriver * drv ...?



qlands
2nd December 2011, 20:52
Hi,

I am using


QSqlDatabase QSqlDatabase::addDatabase ( QSqlDriver * driver, const QString & connectionName = QLatin1String( defaultConnection ) )


http://doc.qt.nokia.com/4.7/qsqldatabase.html#addDatabase-2

to connect to a mysql Embedded database (using my.cnf), here is the code:



#include <QtCore/QCoreApplication>
#include <QtSql>

#include "QMYSQLDriver"
#include <mysql.h>

int main(int argc, char *argv[])
{
//QCoreApplication a(argc, argv);
{
QSqlDatabase mydb;
MYSQL *mysql;

static char *server_options[] = \
{ "mysql_test", "--defaults-file=/home/cquiros/temp/mysql/my.cnf", NULL };
int num_elements = (sizeof(server_options) / sizeof(char *)) - 1;

static char *server_groups[] = { "embedded", NULL };

qDebug() << "Loading embedded";
mysql_library_init(num_elements, server_options, server_groups);
mysql = mysql_init(NULL);
mysql_options(mysql, MYSQL_READ_DEFAULT_GROUP, "embedded");
mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);

mysql_real_connect(mysql, NULL,NULL,NULL, "database1", 0,NULL,0);


//mydb = QSqlDatabase::addDatabase("QMYSQLE","mydb"); //Add the database connector to MySQL

QMYSQLDriver *drv = new QMYSQLDriver(mysql);

mydb = QSqlDatabase::addDatabase(drv,"connection1"); //Add the database connector to MySQL
qDebug() << "Embedded driver added";

mydb.setDatabaseName("test");

if (!mydb.open()) //Try to opens the database
{
qDebug() << "Error while opening the database";
}
else
{
qDebug() << "DB test opened";
QSqlQuery tables(mydb);
QString sql;
sql = "SELECT count(*) FROM system";
if (tables.exec(sql))
{
tables.first();
qDebug() << "Total records is: " << tables.value(0).toString() << " ok.";
}
else
{
qDebug() << tables.lastError().databaseText();
}

}
}
qDebug() << "Closing DB";
QSqlDatabase::removeDatabase("connection1"); // correct
qDebug() << "DB closed";

//return a.exec();
qDebug() << "En of program....";
}


The code works however, there is a segmentation fault when the program finished. If I trace the error it happens is the QMYSQLDriver (from QT sources) when the driver closes:



void QMYSQLDriver::close()
{
if (isOpen()) {
#ifndef QT_NO_THREAD
mysql_thread_end();
#endif
mysql_close(d->mysql); //Here is the failure
d->mysql = NULL;
setOpen(false);
setOpenError(false);
}
}


Any idea what is wrong or if this is not the way to connect using the embedded driver I would appreciate some help.

Thanks,
Carlos.