My project is to program a simple ShopApp. One of the functions is to check if there is a sufficient stock of stocks so that the client can buy the desired amount of what he wants to buy. The functions look like this: ( cart - std::vector<product> , and Pid stands for product identifier):
bool sqlfunctions::checkStock(){ QSqlQuery query; int diff, stock; for(iter cursor = cart.begin();cursor!=cart.end();cursor++){ query.prepare("SELECT stock FROM products WHERE id = cursor->getPid()"); query.exec(); // Need to save result of query into variable stock stock = ??; diff = stock - cursor->getAmount; if(diff < 0){ return false; } } return true; }
Obviously, this function does not work because cursor-> getPid () is not executed because it is a string. So the question here is: how to insert a C ++ variable in sql-query ? In regular C ++, I would use some swprintf_s function. So, a good idea?
Secondly, since both query.exec() and query.prepare() are booleans that return true or false based on success , how can I store the results of queries in a C ++ variable?
Note that I am new to SQL and SQL with Qt. I am using QT5. I already tried to read the documentation about the QSqlQuery class and its functions, BindValue() and addBindValue() seems interesting. However, I really do not understand how they work.
Edit
So now I have a minimal example that doesn't work yet, despite the accepted answer. However, the compiler does not give me any warnings or errors:
void MainWindow::on_ButtonSQL_clicked() { QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("..."); db.setDatabaseName("..."); db.setUserName("..."); db.setPassword("..."); db.setPort(3306); db.open(); QMessageBox msgBox; if (db.open()) { msgBox.setText("It works :)"); msgBox.exec(); } else { msgBox.setText("No connection."); msgBox.exec(); } QSqlQuery query(db); // This query worked! query.exec("INSERT INTO users (id, username, balance) VALUES(25, 'someName', 10000)"); // initialize someNumber to check later, whether it was processed correctly. int id = 2, someNumber = 20; query.prepare("SELECT stock FROM products WHERE id = :myid"); query.bindValue(":myid", id); query.exec(); QString idValue = query.boundValue(0).toString(); someNumber = query.value(0).toInt(); msgBox.setText("The stock is: "+QString::number(someNumber)+"\nThe placeholder has the value: "+idValue); msgBox.exec(); }
Expected msgBox of the last msgBox:
The stock is: 100 The placeholder value is: 2
Actually conclusion:
The stock is: 0 The placeholder value is: 2
If I try instead to select a row (e.g. productName), say using QString myProductName = query.value(0).toString() (and the corresponding changes in the code), return will be an empty string.
** SOLVED: ** See the comment from Floris in the accepted answer. I missed query.next() .