nf313743
nf313743

Reputation: 4227

QSqlQuery Memory issues. QSqlQuery::exec() and QSqlDatabase::open()/close();

I'm checking the memory usage of an application I've made. It makes numerous calls to read and write values to and from a database (SQLite 3). I've observed the following:

For example, here is a typical segment of code I've been using to access my database.

QStringList values;
db.open();
QString strQuery = "SELECT DISTINCT " + field + " FROM " + table + str;

QSqlQuery query(db);
query.prepare(strQuery);

if(query.exec() == true)
{
  while(query.next())
  {
    values.push_back(query.value(0).toString());
  }
}

db.close();

Having experimented with I find the code below 'traps' less memory:

QStringList values;
QString strQuery = "SELECT DISTINCT " + field + " FROM " + table + str;

QSqlQuery query(strQuery, db);

  while(query.next())
  {
    values.push_back(query.value(0).toString());
  }

However, a small amount of memory is still not released. Has anyone else experienced anything like this?

Can I some how release this memory?

P.s. Same happens here, some memory is never released:

db.open();
QSqlQuery query(db);

query.exec("DELETE FROM table1");
query.exec("DELETE FROM table2");
query.exec("DELETE FROM table3");
query.exec("DELETE FROM table4");
...

db.close();

Upvotes: 5

Views: 7449

Answers (3)

hmuelner
hmuelner

Reputation: 8221

From the documentation of QSqlDatabase::addDatabase and QSqlDatabase::database() one can deduce that there is a global variable that manages the database connections. If you look into qsqldatabase.cpp you will find a QConnectionDict.

BTW: Do not construct your SQL queries by concatenating strings, always use prepare and bindValue (SQL injecttion!), if there is any chance that parts of the query come from user input.

Upvotes: 1

Rav
Rav

Reputation: 11

You have to use QSqlQuery.finish () or QSqlQuery.clear before you close the database. Otherwise residual memory is left out in the Query object. It is mentioned in the document that Query object can be used for multiple query. You will noticed the "memory leak".. when you query for 10,000 records. The memory usage goes up drastically.

Upvotes: 1

nf313743
nf313743

Reputation: 4227

It seems that in order to release this memory you must create the QSqlQuery variable as a pointer, and delete this pointer before you close the database:

QStringList values;
db.open();
QString strQuery = "SELECT DISTINCT " + field + " FROM " + table + str;

QSqlQuery *query = new QSqlQuery(db);
query->prepare(strQuery);

if(query->exec() == true)
{
  while(query->next())
  {
    values.push_back(query->value(0).toString());
  }
}

delete query;
db.close();

The memory is then released after the database closes.

Upvotes: 2

Related Questions