Insert data from variables to Database



  • Good morning.

    I am working on a project and while i am able to send numbers to my MYSQL database with this code:

    QSqlQuery query;
    query.prepare("INSERT INTO vathmoi (V_1) "
    "VALUES (10)");
    query.exec(); // this runs it
    

    i can not send data using that code

    QString b;
    b=10;
    QSqlQuery query;
    query.prepare("INSERT INTO vathmoi (V_1) "
    "VALUES (b)");
    query.exec(); // this runs it
    

    So i dont know how to handle that isue cause in the project i am developing all that wich are going to be stored in the db are in variables.

    Thank you in advance.



  • You can reference variables in your quere using bindValue(...):

    query.prepare("INSERT INTO vathmoi (V_1) VALUES (:myValue)");
    query.bindValue(":myValue", b);
    query.exec();
    // ....
    

    See also these examples: http://doc.qt.io/qt-5/sql-sqlstatements.html#inserting-updating-and-deleting-records


  • Qt Champions 2017

    Hi and good morning :)
    Your syntax still looks wrong. ( use syntax as @micland shows)
    and please also use
    if(!query.exec()) {
    qDebug() << "SQL Statement Error" << query.lastError();
    }
    as @the_
    mentions in
    https://forum.qt.io/topic/68149/connect-mysql-database-to-qt-app/4



  • @Lazar1
    Aye! right - as @mrjj said never drop the error handling because you can't be sure that your backend is (still) up and running and works as expected... a useful error handling may prevent a lot of debugging.


  • Qt Champions 2017

    Just a note:
    QString b;
    b=10;
    qDebug() << b;

    Does NOT give u "10" but ascii 10
    b=65
    would give u "A"

    QString b;
    b=QString::number(10);

    Give you "10".



  • Thank you all for your quick and correct ansewrs everything works fine now and i have learned a lot about debuging through your comments and i ll be sure to use it well in my programms. I will now close the topic again thanks for everything


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.