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();
Related
I am trying to take data from six fields on a form and pass the data the user enters into a database (A local SQLite3 database). The ID is an integer and the primary key and the rest are varchars of enough length. After reading a lot of related questions, I still cannot figure out where my code is going wrong. I have confirmation that the program is connected to the database, but I keep getting 'parameter count mismatch'. Where am I going wrong? I'm using Qt 5.15 and C++. The table TOOL exists, as I have it open in SQLite Manager with a test row already inserted.
Below is the function that is supposed to submit the data:
//passes data to database upon clicking submit button
void Add_item::on_submitButton_clicked() {
QString name, location, safety, summary, uses, idNumber;
idNumber = ui->testIdBox->text();
name = ui->nameField->text();
location = ui->locationField->text();
safety = ui->safetyField->text();
summary = ui->summaryField->text();
uses = ui->useField->text();
QSqlQuery qry;
qry.prepare("INSERT INTO TOOLS (TOOL_ID, TOOL_NAME, TOOL_SUMMARY, TOOL_LOCATION, TOOL_USE, TOOL_SAFETY) "
"VALUES (:idNumber, :name, :summary, :location, :uses, :safety)");
//binding all values to prevent sql injection attacks
qry.bindValue(":idNumber", idNumber);
qry.bindValue(":name", name);
qry.bindValue(":summary", summary);
qry.bindValue(":location", location);
qry.bindValue(":uses", uses);
qry.bindValue(":safety", safety);
if(qry.exec()){
QMessageBox::critical(this,tr("Confirmation Message"),tr("Success!"));
}
else {
QMessageBox::critical(this,tr("Confirmation Message"),tr("Error, data was not saved."), qry.lastError().text());
}
connClose();
}
Here is where I connect to the database:
//connecting to database
bool Add_item::connOpen() {
QSqlDatabase mydb = QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("C:/Users/laesc/OneDrive/Documents/ToolBuddy/test.db");
if (mydb.open()) {
ui->statusLabel->setText("Connected!");
qDebug()<<("Connected");
return true;
}
else {
ui->statusLabel->setText("Connection Not Successful...");
qDebug()<<("Not Connected");
return false;
}
}
For future viewers, I ended up reducing the number of parameters to 2 and the query worked. For one reason or another the query didn't work if I tried to bind more than 2 variables. I'm just doing multiple queries.
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"));
I am trying to get an input(username) from user and search for that in my sqlite to find it's password for recovery.
QString username = QInputDialog::getText(this, "Password Recovery", "please enter ur Username here:", QLineEdit::Normal,"myUsername", Q_NULLPTR, Qt::WindowFlags(), Qt::ImhNone);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("/home/arian_press/Qt5.7.0/Projects/APQt_chat/apt.db");
if (db.open())
{
QSqlQuery query;
QString qstr="SELECT username,password,support_email FROM users WHERE username=\""+username+"\";" ;
}
if (query.exec(qstr))
{
QString password=query.value(1).toString();
QString pass = "ur password is:" + password;
Smtp *newMail = new Smtp("arian.press2015#gmail.com",query.value(2).toString()," Your Password",pass);
delete newMail;
QMessageBox messageBox;
messageBox.critical(0,"Error","ur credentials are wrong!");
messageBox.setFixedSize(500,200);
}
else
{
qDebug() << query.lastError().text();
}
db.close();
}
else
{
qDebug() << "Failed to connect to database.";
}
but when i run the program, It doesn't return anything while when I open SQLite file in terminal I can get results.
**update:
U didn't mean what I said. the problem is that I can't use \" in the above code because for the query i need: SELECT username,password,support_email FROM users WHERE username="myusername"
but when I use above code it queries for SELECT username,password,support_email FROM users WHERE username=\"myusername\"
so I can't have any results.so now how can I bring quotation marks in QString?
Never concatenate user input with your queries: that makes you vulnerable to SQL injection. Use prepared statements!
Furthermore, you must use single quotation marks '.
QSqlQuery query;
query.prepare("SELECT username,password,support_email "
"FROM users "
"WHERE username=':username';");
query.bindValue(":username", username);
The } following your QString qstr = ... should be removed.
SQL uses single quotes for strings. Try:
QString qstr="SELECT username,password,support_email FROM users WHERE username='"+username+"';";
There is also a more elegant way:
query.prepare("SELECT username,password,support_email FROM users WHERE username = :username;");
query.bindValue(":username", username);
query.exec();
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();
}