[Qt-interest] QtSql and boundValue() for SELECT results

Tony Rietwyk tony.rietwyk at rightsoft.com.au
Fri Jul 3 07:57:42 CEST 2009


Michal wrote:

> Hi,
> 
> what's the way to use QtQuery.boundValue(':placeholder') for SELECT
> statements? I can't find an example and failed to work it out 
> myself too.
> 
> I tried something like:
> 
> QVariant xyz;
> query.prepare("SELECT xyz AS :xyz FROM table WHERE blah=blah");
> query.bindValue(":xyz", xyz, Qt::Out);
> query.exec();
> while (query.next()) {
> 	xyz = query.boundValue(':xyz');
> 	...
> }
> 
> but it didn't work.
> 
> I fell back to using query.value(0), query.value(1), ... but 
> don't quite
> like this method. I'd prefer to refer to the fields in the 
> resultset by
> name instead of by position.
> 
> Does anybody know how to arrange this?
> 
> Thanks!
> 
> Michal

Hi Michal, 

AFAIK, boundValue only returns the values that you have set with bindValue.
I often use boundValues to debug errors when using bindValue.  I don't think
it has anything to do with getting the results of the query. 

The reason value() doesn't have a string parameter is that running in a
loop, your code will waste a lot of CPU time looking up the index of the
field name string.  So it is much more efficient to lookup the field indexes
before the loop. Eg:

	query.exec("select * from c_chord c order by c.chord_name");

	QSqlRecord rec = qry.record();
	int field_chord_num = rec.indexOf("CHORD_NUM");
	int field_chord_name = rec.indexOf("CHORD_NAME");
	int field_chord_notes = rec.indexOf("NOTES_MP");

	TChord *chord;
	while (qry.next())
	{
		chord = new TChord;
		chord->chord_num = qry.value(field_chord_num).toInt();
		chord->chord_name = qry.value(field_chord_name).toString();
		chord->chord_notes =
qry.value(field_chord_notes).toString();
		list.append( chord );
	}

I agree its painful, and my initial response was to override QSqlQuery and
add some more methods, but the efficiency gained is enormous - at least 10
times faster to execute queries this way. 

Hope that helps, 

Tony.





More information about the Qt-interest-old mailing list