PDA

View Full Version : Help with QT, SQLite, Update Statement



chetu1984
17th March 2011, 18:12
Hi,

I think this is almost a nobrainer , but i am going to ask it anyway as I dont't want to waste any more time on this,

I am using SQlite database in my application and i want to update a value in a table where the value is calculated and stored in a variable . i am wondering how to pass the variables value to the column i want to update ..

my code looks like this



QSqlQuery q;

q.exec("SELECT PRESSURE_HIGH, PRESSURE_LOW FROM PRESSURE_TBL");

q.next();

sensorHigh = q.value(0).toFloat();

sensorLow = q.value(1).toFloat();

sensorRange = qAbs(sensorHigh)+qAbs(sensorLow);

currentanalogIP = ((analogInput)/12);

currentDP = (sensorRange*currentanalogIP)+sensorLow;

q.exec("UPDATE PRESSURE_TBL SET CURRENT_DP = currentDP ");

// I am stuck here ....



I am wondering how to pass the currentDP variable to update the column CURRENT_DP in the table

any help would be highly appreciated,

Thanks.

schnitzel
17th March 2011, 18:36
you're close...
instead of literally assigning the variable 'currentDP' to the field 'CURRENT_DP', you need to assign its *value*. Look at how to bind values:
http://doc.qt.nokia.com/latest/qsqlquery.html#details

You can also do something like this (not tested as I'm not near an actual database):


q.exec(QString("UPDATE PRESSURE_TBL SET CURRENT_DP = %1").arg(currentDP));


make sure that CURRENT_DB has the proper field type that matches the type of currentDP.

good luck

chetu1984
17th March 2011, 18:41
Thank you very much that worked and was of great help...

ChrisW67
17th March 2011, 22:24
I wouldn't get into the habit of constructing SQL as strings: it is open to abuse if the data is in any way untrusted and can fall foul of things like single quotes in parameters. These issues are avoided with bindable parameters:


QSqlQuery qry;
if (qry.prepare("UPDATE PRESSURE_TBL SET CURRENT_DP = :current_dp")) {
qry.bindValue(":current_dp", currentDP);
if (qry.exec())
qDebug() << "Woohoo!";
else
qDebug() << "Update failed";
}
else
qDebug() << "Your SQL is broken";

If you are going to do the update many times (e.g. in a loop) then you should prepare() the query once outside the loop, and just update the bind variables and exec() each time through the loop.