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";
}
}
Related
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
I'm doing Qt application. I am trying save data in database. I have got problem because I have got connection with sqlite3, but when i want insert data QT says that QSqlQuery::prepare: database not open.
void DodajKontakt::on_btn_add_clicked()
{
QSqlDatabase db_kon = QSqlDatabase::addDatabase("QSQLITE");
db_kon.setDatabaseName("C:/Users/Lukasz/Desktop/qt master/organizator/baza_kontakty.db");
QSqlQuery query;
query.prepare( "CREATE TABLE kontakty(ids INTEGER PRIMARY KEY, name TEXT, surname TEXT, company TEXT, email TEXT, phone TEXT");
if(!db_kon.open())
{
qDebug() << "error:" << db_kon.lastError().text();
}
else
qDebug() << "Succsess";
if(ui->lineEdit_name->text().isEmpty() && ui->lineEdit_surname->text().isEmpty()
&& ui->lineEdit_email->text().isEmpty() && ui->lineEdit_phone->text().isEmpty()
&& ui->lineEdit_company->text().isEmpty())
{
QMessageBox::critical(this, tr("Error"), tr("Uzupełnij wszystkie pola!"));
}
else
{
QString name, surname, company, email, phone;
name = ui ->lineEdit_name->text();
surname = ui ->lineEdit_surname->text();
company = ui ->lineEdit_company->text();
email = ui ->lineEdit_email->text();
phone = ui ->lineEdit_phone->text();
query.prepare("INSERT INTO kontakty(name,surname,company.email.phone) VALUES('"+name+"','"+surname+"','"+company+"','"+email+"','"+phone+"')");
if(query.exec())
QMessageBox::information(this, tr("Sukces"),tr("Dodano nowy kontakt"));
else
QMessageBox::information(this, tr("Error"),tr("Nie udalo sie dodac nowego kontaktu"));
}
}
It is results.
QSqlQuery::prepare: database not open
Succsess
Can someone help me?
Your main error is that you are trying to create the table before opening the database, that's why you get that error.
Another error that is repetitive is that even when a problem happens your logic will still want to insert data, what you should do is print an error message and return.
You also have errors in the query, for example in the creation of the table you need to close with a parenthesis.
And finally do not build the query directly if you are going to use data provided by the user since your system will be prone to SQL Injection, it is appropriate to use the bind-value.
QSqlDatabase db_kon = QSqlDatabase::addDatabase("QSQLITE");
db_kon.setDatabaseName("C:/Users/Lukasz/Desktop/qt master/organizator/baza_kontakty.db");
if(!db_kon.open()){
qDebug() << "error:" << db_kon.lastError().text();
return;
}
qDebug() << "Success";
QSqlQuery query;
query.prepare( "CREATE TABLE kontakty(ids INTEGER PRIMARY KEY, name TEXT, surname TEXT, company TEXT, email TEXT, phone TEXT)");
if(!query.exec()){
qDebug()<<"error:" << query.lastError().text();
return;
}
QString name = ui->lineEdit_name->text();
QString surname = ui->lineEdit_surname->text();
QString company = ui->lineEdit_company->text();
QString email = ui->lineEdit_email->text();
QString phone = ui->lineEdit_phone->text();
if(name.isEmpty() &&
surname.isEmpty() &&
email.isEmpty() &&
phone.isEmpty() &&
company.isEmpty())
{
QMessageBox::critical(this, tr("Error"), tr("Complete all fields!"));
return;
}
query.prepare("INSERT INTO kontakty(name, surname, company, email, phone) VALUES(?, ?, ?, ?, ?)");
query.addBindValue(name);
query.addBindValue(surname);
query.addBindValue(company);
query.addBindValue(email);
query.addBindValue(phone);
if(query.exec())
QMessageBox::information(this, tr("Success"),tr(" A new contact has been added"));
else
QMessageBox::information(this, tr("Error"),tr("It was not possible to add a new contact"));
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();
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.
This is the code which has problem:
QMessageBox::information(this, "Connexion Open", "Connexion BD Ok!");
QSqlQuery req;
req.exec("SELECT * FROM reservation");
while(req.next()) {
float id = req.value(0).toFloat();
text2->setText(" "+QString::number(id)+" " );
The message "Connexion BD Ok!" appears perfectly.
How can I retrieve the result of the DB knowing that the DBMS(SGBD) is SQLite?
Thank You
It looks like you are already retrieving the id, so I'm guessing that your question is how you connect to a sqlite database in the first place with Qt. You typically specify the database when you are connecting. Something like:
QSqlDatabase db = QSqlDatabase::addDatabase(ntr("QSQLITE"));
QFileInfo dbPath(pathToDb, dbFileName);
db.setDatabaseName(dbPath.absoluteFilePath());
if (!db.open()) {
qDebug() << ntr("Could not open database:") << db.databaseName();
}
if (db.isOpenError()) {
QSqlError err = db.lastError();
qDebug() << ntr("Last error:") << err.text();
}