Qt QSqlQuery bindValue如何工作?但不是用:占位符

时间:2022-12-25 04:15:09

I'm working with SQLite, doing insert into table. Folowwing

我在使用SQLite,做插入到表格中。跟随

QSqlQuery testQuery(QString("INSERT INTO test(testcol) VALUES(?)"));
testQuery.bindValue(0, someQStringObg);
testQuery.exec();

works, but

有效,但

QSqlQuery testQuery(QString("INSERT INTO test(testcol) VALUES(:val)"));
testQuery.bindValue(":val", someQStringObg);
testQuery.exec();

don't. testQuery.lastError().text() returns No query Unable to fetch row

不喜欢。text()返回无法获取行的查询

Have no clue why things are that way, but really want to find out.

不知道为什么事情是那样的,但真的想知道。

1 个解决方案

#1


7  

Please use prepare as the official example:

请使用prepare作为官方示例:

QSqlQuery testQuery;
testQuery.prepare("INSERT INTO test(testcol) VALUES(:val)");
testQuery.bindValue(":val", someQStringObj);
testQuery.exec();

The reason for the error is that the query was executed before binding to the corresponding placeholder. You can see the relevant part of the constructor documentation:

错误的原因是查询是在绑定到相应的占位符之前执行的。您可以看到构造函数文档的相关部分:

If query is not an empty string, it will be executed.

如果查询不是空字符串,它将被执行。

#1


7  

Please use prepare as the official example:

请使用prepare作为官方示例:

QSqlQuery testQuery;
testQuery.prepare("INSERT INTO test(testcol) VALUES(:val)");
testQuery.bindValue(":val", someQStringObj);
testQuery.exec();

The reason for the error is that the query was executed before binding to the corresponding placeholder. You can see the relevant part of the constructor documentation:

错误的原因是查询是在绑定到相应的占位符之前执行的。您可以看到构造函数文档的相关部分:

If query is not an empty string, it will be executed.

如果查询不是空字符串,它将被执行。