【问题标题】:QSqlQuery does not prepare sql for PostgreSQLQSqlQuery 不为 PostgreSQL 准备 sql
【发布时间】: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


    【解决方案1】:

    您不能为表名使用占位符。您还应该检查 QSqlQuery::prepare() 的返回值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 2016-05-12
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      相关资源
      最近更新 更多