开发者

Got stuck on using prepare() and bindvalue() in c++ Qt

开发者 https://www.devze.com 2022-12-17 02:59 出处:网络
I\'ve written a SQL query based on Qt assistant and it says that you can use the prepare() method instead of exec() then you can pass your parameter by the help of two methods called :

I've written a SQL query based on Qt assistant and it says that you can use the prepare() method instead of exec() then you can pass your parameter by the help of two methods called :

bindvalue() and addbindvalue()

Here is an snippet code of my problem :

Query->prepare("SELECT ID , Row , Col FROM some开发者_Go百科table WHERE Row = :row AND Col = :col");
Query->bindValue(":row" , __Row);
Query->bindValue(":col" ,__Col);
Query->exec();
qDebug("%s" , Query->executedQuery().toStdString().c_str());

output :

SELECT ID , Row , Col FROM sometable WHERE Row = ? AND Col = ?

and also I've used another suggested way :

Query->prepare("SELECT ID , Row , Col FROM sometable WHERE Row = :row AND Col = :col");
Query->addBindValue(0 , __Row);
Query->addBindValue(1 ,__Col);
Query->exec();
qDebug("%s" , Query->executedQuery().toStdString().c_str());

output :

SELECT ID , Row , Col FROM sometable WHERE Row = ? AND Col = ?

but when I use exec() normally it works perfectly and will replace the corresponding values instead of "?".

is there any explanation about that? or should I use the ordinary exec()?


Is the exec() call failing ? Because it may just be ok what you're seeing, as ,depending on which sql server you're using, the binding could be done by the server ( e.g. Oracle ). According to Qt docs, executedQuery: "In most cases this function returns the same string as lastQuery(). If a prepared query with placeholders is executed on a DBMS that does not support it, the preparation of this query is emulated". So, I guess, if the server supports binding values the preparation won't be emulated so you'd just see the query without the placeholders being replaced by real values.


This is just a guess but from http://qt.nokia.com/doc/4.6/qsqlquery.html I read the following:

Warning: You must load the SQL driver and open the connection before a QSqlQuery is created. Also, the connection must remain open while the query exists; otherwise, the behavior of QSqlQuery is undefined.

Is the connection open in your case?


You can try this if you want to how your query constructed with prepared statements:

qDebug("%s" , Query.lastQuery().toStdString().c_str());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号