PDA

View Full Version : SQL JOIN queries & QSqlRecord objects not storing table names



SweetieCakes
23rd July 2010, 17:38
Hi! I'm trying to do a LEFT JOIN query on two tables in my database, and everything works just fine with the QSqlQuery object. However, I've been using the record() method to get an record object for the current row so that I can access the database columns by name instead of index.

However, this doesn't work with multiple tables - the table names are stripped out of the column names. So I can't do something like value("table1.column_name") - instead, the column names are mixed with each other.

What should I do?

saa7_go
24th July 2010, 05:27
You can use QSqlQuery::value(int index) (http://doc.trolltech.com/4.6/qsqlquery.html#value) to get the value of field index in the current record.



query.exec("SELECT ....");
query.next();
qDebug() << query.value(0).toInt() << query.value(1).toString(); // just an example

SweetieCakes
24th July 2010, 15:21
You can use QSqlQuery::value(int index) (http://doc.trolltech.com/4.6/qsqlquery.html#value) to get the value of field index in the current record.



query.exec("SELECT ....");
query.next();
qDebug() << query.value(0).toInt() << query.value(1).toString(); // just an example

The problem is that I need to use real field names, not indexes.

saa7_go
24th July 2010, 18:57
So I can't do something like value("table1.column_name")...


Does these codes:


QSqlQuery qry;
qry.exec("SELECT * FROM table1");
qry.next();
qDebug() << qry.record().value("table1.col_name").toString();

work for you?

When i tried that, the output from qDebug() is "". But, if i call


qDebug() << qry.record().value("col_name").toString();

the output is correct.

wysota
25th July 2010, 00:49
If you know up front that you'll be making the joins then there should be no problem in creating your own map which will let you access fields by names that will be converted to indexes in the record and fed to QSqlValue::value()

SweetieCakes
25th July 2010, 10:47
If you know up front that you'll be making the joins then there should be no problem in creating your own map which will let you access fields by names that will be converted to indexes in the record and fed to QSqlValue::value()
My temporary solution is to have a QList of QString's (the column names) and building the query using it and then getting the right indexes using indexOf(): However, this turned something that took 10-20 lines of code to double of the original size.

Is there really no way to make QSqlRecord not forget the table prefixes?