PDA

View Full Version : Best practice to pass parameters to a QSqlQueryModel



toufic.dbouk
7th September 2013, 00:10
Hello friends,
can anyone state the best practices for passing one or more parameters to a QSqlQuery
and specially to a QSqlQueryModel ?
for example : you have a QString name , lastName
query in english language : select Name , Lastname ,... from table people where Name = name and Lastname = lastName
so that the query can take the name and last name from the users input and search of the record
any help would be appreciated.
Thanks in advance.

zerokewl
7th September 2013, 12:03
I think there is only 2 ways to perform a QSqlQuery anyways, you either use either.


QString name = "John";
QString lastname = "Smith";

QString sql = "SELECT * FROM people WHERE Name = '" + name + "' AND LastName = '" + lastname + "'";
QSqlQuery.exec(sql);
or
you can prepare a statement then exec it..

QSqlQuery.prepare("SELECT * FROM people WHERE Name = :name and LastName = :lastname);
QSqlQuery.bindValue(":name", name);
QSqlQuery.bindValue(":lastname", lastname);
QSqlQuery.exec();

Note* Please correct me if there is another way, but this gets the job done for me.
I only use Prepare statements when inserting data other than text, like QByteArray / Data.

toufic.dbouk
7th September 2013, 12:55
Hi there ,
im not aware of any other methods to do that, basically i use the first suggestion but
i was searching on other forums and i found out that that way doesn't take care of Sql Injections
you can check that forum your self here http://forums.asp.net/t/1718846.aspx there is an argument about it
so i started this thread to know what is the best way to do that in Qt using QSqlQueryModel and QSqlQuery
i guess the 2nd suggestion takes care of the Sql Injections and some other bad habits
thanks for your reply

zerokewl
7th September 2013, 13:06
I normally use QSqlQueryModel this way,


QString sql = "SELECT * From [myView] WHERE [NB]='144846'";
QSqlQueryModel *model = new QSqlQueryModel();
model->setQuery(sql, databaseConnection);
tableview->setModel(model);

toufic.dbouk
7th September 2013, 13:12
something like this might do the job:

QSqlQuery Pqry;
Pqry.prepare("SELECT * From [CarPlate09].[dbo].[myView] WHERE [ACTUALNB]=:number");
Pqry.bindValue(":number",Number);
QSqlQueryModel * model = new QSqlQueryModel;
Pqry.exec();
model->setQuery(Pqry);
QTableView *view = new QTableView;
view->setModel(model);
view->show();

yea i noticed that i didnt type the exec command but then i edited the post and fixed it
thanks friend , keep in touch

and friend use the code tags for better reading and understanding of code, it helps alot.
best reagrds