[Qt-interest] problem with QSqlQuery

Sean Harmer sean.harmer at maps-technology.com
Tue May 25 15:59:37 CEST 2010


Hi,

On Tuesday 25 May 2010 14:35:01 mierdatutis mi wrote:
> Hi,
> 
> I'm trying to do a select of a database like this:
> 
> db.setHostName("xx.xx.xx.xx");
>       db.setDatabaseName("prueba");
>       db.setUserName("xxxxxxx");
>       db.setPassword("yyyyyy");
>       if (!db.open())
>       {
>       QMessageBox::information(this, "Application name","not connected");
>       QMessageBox::information(this,"",db.lastError().text());
>       }
> 
>       QSqlQuery query;
> 
>       if( db.open() ) {
>       query = QSqlQuery("select * from USERSGROUPS");
>       bool prueba = query.exec();
>       qDebug() << query.lastError().text();
>       QMessageBox::information(this,"",query.lastError().text());
>  ............................
> ..........................
> ...........................
> 
> it gives me: [Microsoft][ODBC controllers admin] Function sequence error
> QODBC3: Unable to execute statement
> 
> Could you help me please?
> Many thanks and sorry for my english!

When you construct a QSqlQuery the way you have ie:

query = QSqlQuery("select * from USERSGROUPS");

the query is immediately executed according to the docs. You are then calling 
exec() on it again.

Also it is not recommended to use "SELECT *" type queries as the number and 
order of columns returned is not necessarily fixed. Better to explicitly list 
the columns in your query.

Instead for example try it like this:

QSqlQuery query;
if ( query.exec( "SELECT group, gid, user, uid FROM USERGROUPS" ) )
{
    // Process results
    while ( query.next() )
    {
        QString group = query.value( 0 ).toString();
        int gid = query.value( 1 ).toInt();
        QString user = query.value( 2 ).toString();
        int uid = query.value( 3 ).toInt();
    }
}
else
{
    // Error handling goes here
}

Obviously replace my imaginary column names with your actual column names.

HTH,

Sean



More information about the Qt-interest-old mailing list