PDA

View Full Version : QT SQLITE Query



andrewhopps
14th May 2015, 23:23
I am quite confused what is going on here and I have to be completely missing something stupid, but...



mydb.open();
QSqlQuery query;
query.prepare("select * from inventory");
query.exec();

A simple query to my database that works in numerous other places, just does not function at all in one of my pushbutton slots.


0x14bfed30 //Query Result
" " //Query Error


val = ui->listView->model()->data(index).toString();
mydb.open();
QSqlQuery query;
query.prepare("select * from inventory where item ='"+val+"'");

if(query.exec())
{
while(query.next())
{
ui->lineEdit_shelf->setText(query.value(1).toString());
ui->lineEdit_container->setText(query.value(2).toString());
ui->lineEdit_finished->setText(query.value(4).toString());
ui->lineEdit_unfinished->setText(query.value(5).toString());
ui->textEdit_notes->setText(query.value(6).toString());
if(query.value(3) == 1)
ui->checkBox->setChecked(true);
else
ui->checkBox->setChecked(false);
}
mydb.close();
}
else
qDebug() << query.lastError().text();

}

Example of setup in a listView_clicked slot. But it functions perfectly well. Any kind of guidance would be greatly appreciated, as this problem popped up while I was attempting to make an update query, and it seems to be a much bigger issue.

jefftee
15th May 2015, 01:50
A couple of general comments about your code shown above:


You don't show your call to QSqlDatabase::addDatabase
You don't verify that your database has even opened successfully. Obviously if that fails, nothing else can be expected to work.
You should use the QSqlQuery constructor that uses your QSqlDatabase object
You should not build your SQL statements using values obtained by the user. It leaves you susceptible to SQL injections. Use instead positional or named parameters for placeholders in your SQL statements, then QSqlQuery::prepare your SQL statement, then finally use QSqlQuery::bindValue to bind the values to their positional or named parameters before you QSqlQuery::exec the query.


Make those changes and if you still have a problem, re-post please.