【发布时间】:2020-03-11 14:56:15
【问题描述】:
我正在尝试使用 QSqlQuery 准备 sql 查询,但是对于每个 sql,我都会收到关于 EXECUTE 语法的错误。
这里我正在连接数据库:
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("localhost");
db.setDatabaseName("test_db");
db.setUserName("postgres");
if (!db.open())
{
qWarning() << "DB not opened";
return;
}
这里准备sql:
QString str { "INSERT INTO :table (test_text, test_int) VALUES (:txt, :int)" };
QSqlQuery query(db);
query.prepare(str);
query.bindValue(":table", "test_table");
query.bindValue(":txt", "test");
query.bindValue(":int", 1);
然后我执行准备好的查询
if (!query.exec())
{
qWarning() << query.lastError();
} else {
qWarning() << "success!";
}
并且出现错误:
QSqlError("42601", "QPSQL: Unable to create query", "ERROR: syntax error at or near: \"(\")\n第 1 行:EXECUTE ('test_table', NULL, NULL) \n ^\n(42601)"
但下一个代码有效:
query.exec(QStringLiteral("INSERT INTO %1 (test_text, test_int) VALUES (%2, %3)").arg("test_table").arg("'test'").arg(1))
我曾经使用 MySQL,它运行良好。
【问题讨论】:
标签: c++ postgresql qt