相关文章推荐
很酷的南瓜  ·  Alluxio ...·  1 年前    · 
安静的黄豆  ·  MySQL select ...·  1 年前    · 
千杯不醉的核桃  ·  winapi lb_setcursel-掘金·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm writing a program in QT and have a problem with writing an SQL query Select. I have a simple table which contains columns like: ID, name_or_nickname, surname, occupation. I have 3 variables I want to use in the query:

QString name = "Peter";
QString surname = "Smith"; 
QString occupation = "New York";

I want to run this query using those variables:

 QSqlDatabase sql;                                                 
 QSqlQuery query(sql);
 QString execute = "SELECT COUNT(name) FROM table1 WHERE name_or_nickname='?' AND surname='?' AND occupation='?';";
        query.prepare(execute);
        query.bindValue(0, name);
        query.bindValue(1, _surname);
        query.bindValue(2, _occupation);
        query.exec();
        if (query.next()) 
            rows= query.value(0).toInt();
            return true;
            qDebug() << query.lastError();
            return false;

However it doesn't work and isActive() function returns false, so there's something wrong with the query - probably with the brackets. Could you show me an example how should I deal with it? Thank you in advance!

===========================================================================

I post here the necessary code:

MainWindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <person.h>
#include <QMainWindow>
#include <QString>
#include <QtDebug>
#include <QtSql>
namespace Ui {
class MainWindow;
class MainWindow : public QMainWindow
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private slots:
    void on_pushButton_1_clicked();
private:
    Ui::MainWindow *ui;
    QSqlDatabase sql;
    bool open_or_not;
#endif // MAINWINDOW_H

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    ui->setupUi(this);
    sql = QSqlDatabase::addDatabase("QSQLITE", "db");
    sql.setDatabaseName("E:\\folder\\database.sqlite3");
    sql.close(); // this was called beacuse of the problem with first query
    sql.open();
    QSqlQuery query(sql);
    QString execute = "CREATE TABLE IF NOT EXISTS table1 (id INTEGER UNIQUE PRIMARY KEY, name_or_nickname TEXT, surname TEXT, occupation TEXT);";
query.exec(execute);
    qDebug() << "isActive: CREATING TABLE" << query.isActive();
    query.clear();
    open_or_not = sql.open();
MainWindow::~MainWindow()
    delete ui;
void MainWindow::on_pushButton_1_clicked()
    if(open_or_not)
        Person person1(_sql, Johnny, Walker, California, this);
        bool result = false;
        result = person1.search_in_database();
        qDebug() << result;

Person.h:

#ifndef PERSON_H
#define PERSON_H
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QtDebug>
#include <QDebug>
#include <QJsonDocument>
#include <QtSql>
namespace Ui {
class Person;
class Person : public QDialog
    Q_OBJECT
public:
    explicit Person(QSqlDatabase & sql, QString name_or_nickname, QString surname, QString occupation, QWidget *parent);
    ~Person();
    bool search_in_table();
private:
    Ui::Person *ui;
    QSqlDatabase sql;
    QString name_or_nickname;
    QString surname;
    QString occupation;
#endif // PERSON_H

Person.cpp:

#include "person.h"
#include "ui_person.h"
Person::Person(QSqlDatabase & sql, QString name_or_nickname, QString surname, QString occupation, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Person)
    ui->setupUi(this);
    this->sql = sql;
    this->name_or_nickname = name_or_nickname;
    this->surname = surname;
    this->occupation = occupation;
Person::~Person()
    delete ui;
bool Person::search_in_table()
    QSqlQuery query(sql);
    int rows = 0;
    QString name = this->name_or_nickname;
    QString _surname = this->surname;
    QString _occupation = this->occupation;
    QString execute = "SELECT COUNT(name) FROM table1 WHERE name_or_nickname='?' AND surname='?' AND occupation='?';";
    query.prepare(execute);
    query.bindValue(0, name);
    query.bindValue(1, _surname);
    query.bindValue(2, _occupation);
    query.exec();
    if (query.next()) 
        rows= query.value(0).toInt();
        return true;
        qDebug() << query.lastError();
        return false;

Main.cpp:

#include "mainwindow.h"
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
                Added missing brackets at the end of the line with QString execute, still doesn't work actually...
– The_Long_Distance_Runner
                Jan 12, 2019 at 21:17
                I see that you use QSqlDatabase _sql; But in what part do you set the configuration and open the connection?`
– eyllanesc
                Jan 12, 2019 at 21:57
                Well, I have 2 classes- MainWindow and Person. I set the configuration in the constructor of MainWindow and pass _sql parameter when creating objects of Person in MainWindow class. So I think everything should work fine
– The_Long_Distance_Runner
                Jan 12, 2019 at 22:30
                Well, as you did not point out in your question for me it is a point that can cause the error.
– eyllanesc
                Jan 12, 2019 at 22:39
                But what can cause this problem? I have even already tried passing this parameter by the reference, but it hasn't changed anything. Any other suggestions?
– The_Long_Distance_Runner
                Jan 12, 2019 at 22:44

Better use query with parameters to prevent different type convertation issues in SQL

QString execute = "SELECT COUNT(name) FROM table1 WHERE surname=? AND occupation=?;";
QSqlQuery query;
query.prepare(execute);
query.bindValue(0, surname);
query.bindValue(1, occupation);
query.exec();
if (query.next()) {
    rows= query.value(0).toInt();
} else {
    qDebug() << query.lastError(); //check your error here
                Query looks good... Maybe try to quote your field names. Like "SELECT COUNT('name')...". Maybe DBMS you use has system keyword called name
– Serhiy Kulish
                Jan 12, 2019 at 22:24
                To be honest I just put the simple name of this variable, just to let you see how it work - the full name is: name_or_nickname, so I don't think DBMS can know this ;-) any other ideas?
– The_Long_Distance_Runner
                Jan 12, 2019 at 22:33
QSqlDatabase _sql;                                                 
QSqlQuery _query(_sql);
QString execute_stat = "SELECT COUNT(name) FROM table1 WHERE surname='%1' AND 
occupation='%2';";
_query.prepare(execute_stat.arg(surname, occupation));
q.exec();
int rows= 0;
if (q.next()) {
    rows= q.value(0).toInt();
                you won't use isActive() to know the count of Name the count will be stored in rows variable
– Mohamed Sayed Abdalaziz
                Jan 12, 2019 at 21:58

Yours :

QString execute = "SELECT COUNT(name) FROM table1 WHERE surname='%1' AND occupation='%2';

Should Be :

QString execute = "SELECT COUNT(name) FROM table1 WHERE surname='%1' AND occupation='%2';"
                Yeah, sure, but I made this mistake only here, on StackOverflow. In my program I have it. What do you sugest?
– The_Long_Distance_Runner
                Jan 12, 2019 at 21:13

To be honest, I don't know why neither of the suggested methods above did the job.

However, the simpliest version worked for me:

QString execute = "SELECT COUNT(*) FROM table1 WHERE (name_or_nickname='" + name + "') AND (surname='" + surname + "') AND (occupation='" + occupation + "');";

Thank you for all your help.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.