T
T
tschin2017-07-09 21:37:02
Qt
tschin, 2017-07-09 21:37:02

Why are values ​​not substituted through bindValue in QSqlQuery?

Hello! I'm trying to add data to the database via bindValue, however, the data is not being bound.
I do this:

if(query.prepare("INSERT INTO messages (date, time, username, phone_number, text_message) VALUES (:date, :time, :name, :phone, :text)"))
    {
        query.bindValue(":date","1");
        query.bindValue(":time","1");
        query.bindValue(":name","1");
        query.bindValue(":phone","1");
        query.bindValue(":text","1");
        qDebug()<<query.lastError();
        query.exec();
}

then through
qDebug()<<query.executedQuery();
I look request. And I see this:
"INSERT INTO messages (date, time, username, phone_number, text_message) VALUES (?, ?, ?, ?, ?)"

I also output this:
qDebug()<<query.boundValues();
I see this:
QMap((":date", QVariant(QString, "1"))(":name", QVariant(QString, "1"))(":phone", QVariant(QString, "1"))(": text", QVariant(QString, "1"))(":time", QVariant(QString, "1")))

Question: why are values ​​not inserted into the request text through bindValue, but question marks remain?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ighor July, 2017-07-09
@tschin

query.executedQuery() won't show the real query, try this:

QString lastQuery = query.executedQuery();
    for (int i = 0, j = 0; j < query.boundValues().size(); ++j)
    {
        i = lastQuery.indexOf(QLatin1Char('?'), i);
        if (i <= 0)  break;
        const QVariant& var = query.boundValue(j);
        QSqlField field(QString(""), var.type());
        if (var.isNull())  field.clear();
        else  field.setValue(var);
        QString formatV = query.driver()->formatValue(field);
        lastQuery.replace(i, 1, formatV);
        i += formatV.length();
    }
qDebug()<<"SQL Query error:"<<lastQuery;

E
eeiaao, 2017-07-09
@eeiaao

bool ok = query.prepare("INSERT INTO messages (date, time, username, phone_number, text_message) VALUES (:date, :time, :name, :phone, :text)");
query.bindValue(":date","1");
query.bindValue(":time","1");
query.bindValue(":name","1");
query.bindValue(":phone","1");
query.bindValue(":text","1");

if (ok)
    query.exec();
else
    qDebug()<<query.lastError();

P
Pavel Mikhalovsky, 2017-07-10
@pavel9609

Make an else branch after prepare and display query.lastError() via qDebug() and see what it says to you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question