View Full Version : SQL query
JD2000
19th November 2009, 18:51
Hi Folks,
A hopefully simple question!
With QSqlQuery a database can be updated with bound values eg:
QSqlQuery query;
query.prepare("INSERT INTO people(ID,Name,Age) "
"VALUES (?, ?, ?)");
query.addBindValue(1);
query.addBindValue("Fred Bloggs");
query.addBindValue(21);
query.exec();
How is this done with a QSqlQueryModel ?
Thanks
montuno
20th November 2009, 10:03
Yes, you can do this with QSqlQueryModel. But, I'm afraid, not in the (simple) way you are expecting. QSqlQueryModel doesn't do such things automatically, it is 'only' a box or a container for holding data.
1) If your data comes from a single table, then QSqlTableModel will do the job for you (Query, Insert, Update, Delete). Why? Because it's easy to abstract the sql queries for a single table.
2) Is the data coming from multiple tables, then Qt simple doesn't know 'magically', where the data is coming from and, for example, which model-colum is representing which attribut on which table. The 'only' help in this case you got is: QSqlQueryModel provides a simple way for filling the model with data by passing a Sql-query to it.
JD2000
20th November 2009, 10:04
I had assumed that something along the lines of
QSqlQueryModel *model = new QSqlQueryModel(this);
QSqlQuery query;
query.prepare("INSERT INTO INSERT INTO people(ID,Name,Age) VALUES (?, ?, ?)");
query.addBindValue(1);
query.addBindValue("Fred Bloggs");
query.addBindValue(21);
model->setQuery(query);
would do the trick but 'query.lastQuery()' seems to indicate that the values are not being bound.
JD2000
20th November 2009, 10:08
Thanks montuno,
I'll try the the QSqlTableModel you suggest.
JD2000
1st December 2009, 14:21
Actually I've discovered that the following works!
QSqlQuery query;
query.prepare("INSERT INTO INSERT INTO people(ID,Name,Age) VALUES (?, ?, ?)");
query.addBindValue(1);
query.addBindValue("Fred Bloggs");
query.addBindValue(21);
query.exec();
model->setQuery("SELECT * FROM clients ORDER BY clientName");
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.