Antonio Pérez
Antonio Pérez

Reputation: 6982

QSqlQuery: get prepared statement string before execution

For testing purposes, I'm trying to get the prepared statement string out of a QSqlQuery object before actually running it.

I have checked lastQuery() and executedQuery() methods, but none of them work.

void foo(QSqlQuery& q)
{
    QString statement = q.lastQuery();
    // statement is empty unless exec() is called
}

QSqlQuery q(myDb);
q.prepare("SELECT * FROM Foo;");
foo(q);

I'd like a way to get back the prepare() parameter string.

Upvotes: 4

Views: 3316

Answers (2)

martinarroyo
martinarroyo

Reputation: 9701

Having a look at the Qt source code, I found where the string ends up in the prepare method:

...
if (query.isEmpty()) {
    qWarning("QSqlQuery::prepare: empty query");
    return false;
}
#ifdef QT_DEBUG_SQL
    qDebug("\n QSqlQuery::prepare: %s",query.toLocal8Bit().constData());
#endif
return d->sqlResult->savePrepare(query);

In which sqlResult is a private QSqlQueryPrivate object. So I would say it might be complicated to get the string from there.

However, a solution comes to my mind. Subclass QSqlQuery, setting a QString attribute which will hold the prepared statement. Then redefine the QSqlQuery::prepare() so it stores the value in the attribute, and then does the original job:

bool TestQSqlQuery::prepare(const QString& query){
    this->m_preparedQuery = query;
    return QSqlQuery::prepare(query);
}

Then create a getPreparedQuery method to retrieve the value at any given time.

I don't think it is a 'clean' solution, but it might help you nonetheless.

Upvotes: 5

Alexander Sorokin
Alexander Sorokin

Reputation: 741

q.executedQuery();

Will return prepared query.

Upvotes: -2

Related Questions