0

I'm trying to prepare sql query with QSqlQuery, but for every sql i'm getting an error about EXECUTE syntax.

Here I'm connecting to database:

QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("localhost");
db.setDatabaseName("test_db");
db.setUserName("postgres");

if (!db.open())
{
    qWarning() << "DB not opened";
    return;
}

And here preparing 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);

Then I execute prepared query

if (!query.exec())
{
    qWarning() << query.lastError();
} else {
    qWarning() << "success!";
}

And an error occurs:

QSqlError("42601", "QPSQL: Unable to create query", "ERROR: syntax error at or near: \"(\")\nLine 1: EXECUTE ('test_table', NULL, NULL)\n ^\n(42601)"

But next code works:

query.exec(QStringLiteral("INSERT INTO %1 (test_text, test_int) VALUES (%2, %3)").arg("test_table").arg("'test'").arg(1))

I used to work with MySQL and it works perfectly.

1 Answer 1

2

You can't use a placeholder for the table name. Also you should check for the return value of QSqlQuery::prepare()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.