C++ / Qtcreator /UPDATE data base - c++

Hello everyone i'm working in a graphical interface application and i face a problem when i want to edit my database.
void livraisonDialog::on_editBtn_clicked()
{
int CIN = ui->cin->text().toInt();
QString NOM_LIVREUR = ui->nomLivreur->text();
QString ADRESSE = ui->adresse->text();
int TEL_LIVREUR = ui->telLivreur->text().toInt();
QString DIPLOME = ui->diplome->text();
QSqlQuery qry;
qry.prepare("UPDATE LIVRAISONS SET (CIN,NOM_LIVREUR,ADRESSE,TEL_LIVREUR,DIPLOME)"
"VALUES (?,?,?,?,?)"
"WHERE CIN=?;"
);
qry.addBindValue(CIN);
qry.addBindValue(NOM_LIVREUR);
qry.addBindValue(ADRESSE);
qry.addBindValue(TEL_LIVREUR);
qry.addBindValue(DIPLOME);
if(qry.exec()){
QMessageBox::information(this,"Done", "information Updated");
}else{
QMessageBox::information(this,"ERROR", "information not UPDATED");
}
}

You are using a wrong query, the right update query is like this:
update table set column1 = 'value1', column2 = 'value2' where condition

Related

How to get the id of the current text in Qt c++ Combobox?

Please help. I am a beginner. This is my slot. I want the id value of the currentText(). The id column is from DepartmentTbl Table. Thank you very much
void addteacherform::on_newTeacherButton_clicked()
{
dbRepository dr;
dr.OpenDBConnection();
//retrieve data from field
QString fname = ui->firstnameEdit->text();
QString mname = ui->middleIEdit->text();
QString lname = ui->lastnameEdit->text();
QString department = ui->DepartmentCombo->currentText();
//insert query
QSqlQuery qry1;
qry1.prepare("INSERT INTO InstructorTbl (InsFname, InsMname, InsLname, DepartmentID)"
"VALUES (:InsFname, :InsMname, :InsLname,:DepartmentID)");
qry1.bindValue(":InsFname",fname);
qry1.bindValue(":InsMname",mname);
qry1.bindValue(":InsLname",lname);
qry1.bindValue(":DepartmentID",department);
if(qry1.exec()){
QMessageBox::information(this,"Added", "Data Added Successfully");
}
else{
qDebug() << "add data failed: " << qry1.lastError();
}
dr.CloseDBConnection();
}
you can use combobox->itemData(combobox->currentIndex()) for current selected text and for current selection id use combobox->currentIndex()
when combobox add item, you can use setItemData:
setItemData(0, "ID1", Qt::UserRole+1);
when itemChanged, you can get id value use itemData:
itemData(0, Qt::UserRole+1);

Qt - Update issue to Sqlite using multiple query

I'm trying to update a row in a SQlite DB through QT and my query doesn't execute even though I tested it in my db manager where it works so I'm confused.
You'll find the code below :
void DataBase::automatisationQteStock(Liste_Commande listeCommande){
if(db.isOpen()){
QSqlQuery query;
QSqlQuery query2;
QString querySelectIdCompo = "select Id_Composition from Carte_composition cc where Id_Carte = :idcarte ;";
QString queryUpdate = "update Stock set quantite = quantite - dose from (select quantite as dose, Id_Stock from Composition where Id_Composition = :tmp) where Stock.Id_Stock = (select Id_Stock from Composition where Id_Composition = :tmp);";
query.prepare(querySelectIdCompo);
query.bindValue(":idcarte", listeCommande.getId_Carte());
query.exec();
while(query.next()){
qint8 tmp = query.value("Id_Composition").toInt();
qDebug() << tmp;
query2.prepare(queryUpdate);
query2.bindValue(":tmp",tmp);
query2.exec();
qDebug() << "Transaction reussie";
}
}
else
{
qDebug() << "Connexion avec la database n'est pas établie";
}
}

QSqlQuery not working

So I have this problem basically, I cannot exec my QsqlQuery.
I am connected to a SQLite database and I have checked that it is really connected.
QString databaseName = QFileDialog::getOpenFileName(this,tr("Open database"),
"",
tr("Databáze (*.db)"));
mydb = QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("databaseName");
if (!mydb.open()) {
ui->statusBar->showMessage("Databáze nebyla připojena!",2000);
databaseCheck = false;
}
else if (mydb.open()) {
ui->statusBar->showMessage("Databáze byla úspěšně připojena.",2000);
databaseCheck = true;
}
This is part of the code from the Mainwindow.cpp which sets up the database connection. The database is declared in mainwindow.h, all is functioning in this part.
Here I got a form which returns some data about an employee that I want to create in the database. databaseCheck is a bool that tells me if the database is connected properly. And those variables name, surname etc. in this case are declared in mainwindow.h as QString.
if (databaseCheck) {
form = new Form(this);
form->setWindowTitle("Formulář informací o zaměstnanci.");
form->exec();
name = form->getName();
surname = form->getSurname();
id = form->getId();
date = form->getDate();
telephone = form->getTelephone();
salary = form->getSalary();
state = form->getState();
QSqlQuery query(mydb);
query.prepare("INSERT INTO employees (jmeno,prijmeni,datumnarozeni,telefon,plat,stav) "
"VALUES (:name, :surname, :date, :telephone, :salary , :state)");
query.bindValue(":name", name);
query.bindValue(":forename", surname);
query.bindValue(":date", date );
query.bindValue(":telephone", telephone);
query.bindValue(":salary", salary);
query.bindValue(":state", state );
query.exec();
}
After I fill up the form with some data about the employee and accept it, it does not send anything to the database. I am checking the database with DB Browser for SQLite and the table employees is totally empty. Can anybody help me?
Your SQL seems correct, the best approach is probably to write something like this.
if (!query.exec())
qDebug() << query.lastError();

Select query returns "value: not positioned on a valid record" in Qt

I have been working on a small code which is supposed to fill up columns on a QTableWidget with values fetched from a SQL table.
Here's a small snippet:
QString path = "C:\\ENTRIES.db";
QString itemToSearch = "ABC"; //This comes as a parameter to a slot actually, assigning it here for simplicity
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(path);
db.open();
QSqlQuery query(db);
query.prepare("SELECT * FROM METADATA WHERE ITEM LIKE ':item %'");
query.bindValue(":item", itemToSearch);
if(query.exec())
{
ui->tableWidgetSearchResults->setVisible(true);
ui->tableWidgetSearchResults->clearContents();
int rCount = ui->tableWidgetSearchResults->rowCount();
while(query.next())
{
ui->tableWidgetSearchResults->setRowCount(rCount + 1);
QTableWidgetItem *qtwParamName = new QTableWidgetItem;
qtwParamName->setFlags(qtwParamName->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsEditable);
qtwParamName->setText(query.value(0).toString());
ui->tableWidgetSearchResults->setItem(rCount, 0, qtwParamName);
QTableWidgetItem *qtwParamValue = new QTableWidgetItem;
qtwParamValue->setFlags(qtwParamValue->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsEditable);
qtwParamValue->setText(query.value(1).toString());
ui->tableWidgetSearchResults->setItem(rCount, 1, qtwParamValue);
rCount++;
}
}
else
{
qDebug() << "Error message: " << query.lastError().text() ;
ui->tableWidgetSearchResults->setHidden(true);
}
db.close();
When executing query.value(<index here>).toString()); lines, the Application Output prints:
QSqlQuery::value: not positioned on a valid record
QSqlQuery::value: not positioned on a valid record
I'm not sure of what I am missing here.
Note: I am using Qt 5.6, MSVC 2013 compiler and SQLite 3.8.
#CL. Thanks for the hint. I tried this line and it worked:
query.prepare("SELECT * FROM METADATA WHERE ITEM LIKE '" + itemToSearch + "%'");
Apparently bindValue was inappropriate in this case.

QSqlQuery.record() is always empty

I'm editing the database in this manner:
QSqlQuery query;
query.prepare("UPDATE student "
"SET name = ? "
"WHERE id = ?");
QString name = "t";
int id = 3;
query.addBindValue(name);
query.addBindValue(id);
query.exec(); // query exec returns true
QSqlRecord record = query.record(); // but the record is empty!
mTableModel->beforeInsert(record);
The retrieved record is always empty, but the QSqlTableModel still changes! I need the record to be valid because I'm trying to synchronize an sql db with a std::vector.
I'm connecting to the database like this:
mDatabase = QSqlDatabase::addDatabase("QSQLITE");
mDatabase.setDatabaseName("database.db");
mDatabase.open();
I tried calling QSqlQuery::clear(), QSqlQuery::finish() but it didn't help. I also tried to open and close the DB, but it also didn't help. What can I do? :\
Qt is not a pain indeed.
All your code is good. The only wrong assumption is that an update request will automatically give you back the updated record. You have to make a new select request on this id to get the updates data in a QSqlRecord.
//[untested]
QSqlQuery select;
select.prepare("SELECT * from student where id = ?");
select.addBindValue(id);
if (select.exec() && select.next()) {
QSqlRecord record = select.record();
}