[PyQt] QSql lastError() must be called BEFORE exec_() ??

Andreas Pakulat apaku at gmx.de
Sat Sep 5 12:49:41 BST 2009

On 04.09.09 17:23:32, Mario Daniel Carugno wrote:
> Hi list, i'm coding my first PyQt4-Sql application, and i can't
> understand a strange behavior.
> I'll write a snippet of code with an erroneous Sql syntax, and i hope
> then to catch the error
> text and display it, in order to know what happened:
> query = QSqlQuery()
> query.prepare("insert inta table (name) values ('myname')")  # note
> that 'inta' is an error
> query.exec_()
> if query.isActive() == False:
>    print "ERRSQL " + str(g_session.db.lastError().text())
> And this do not work ! It is not displaying any text.
> To get it work, i must get the error string BEFORE the execution of the query !!
> query = QSqlQuery()
> query.prepare("insert inta table (name) values ('myname')")  # i made
> an erroneous sql
> query.exec_()
> errorstr = str(query.lastError().text())
> if query.isActive() == False:
>    print "ERRSQL " + errorstr
> Is that behavior normal ??


> How can PyQt get the error's text BEFORE executing the sql statement ?

It doesn't. The errors is fetched _after_ executing the sql statement
because you're executing the sql statement in the line that calls
exec_(). If you look at the API docs it pretty clearly states that
this method executes the prepared sql statement.

The reason the error can be fetched at this point already is because
there's a syntax error in your SQL, thats usually checked very very
early during statement execution, hence after the exec_() call the error
is already set.

If you'd have a long-running query (huge resultset from a select) and
that throws some kind of error way after it was started you'd probably
get the error only after isActive returns false.

> This is very strange for me, don't you think ?
> It toke to me a long time to figure out how that works, because it
> don't seems to be
> logic. I mean, it's supposed that errors can be catched AFTER the
> execution of a statement,
> not BEFORE.

Well, that statement is never executed, because it already errors while
parsing it in the database.


You look tired.

More information about the PyQt mailing list