Qt 和 SQLite:使用数组元素进行过滤

Qt and SQLite: filter using the elements of an array

我目前正在做一个项目,我对 Qt 和 SQLITE 还很陌生。我目前有一个整数数组,想用它来获取链接到数组中元素的数据。例如数据为61616,则输出Sarah.

query.prepare("SELECT name,memberType FROM members WHERE id = :id");
for(index = 0; index < dateIndex; index++)
{
    id = idAr[index];
    query.addBindValue(id);
    query.exec();
}

model2->setQuery(query);
ui->tableView_10->setModel(model2);

我知道这是错误的。有人可以解释如何正确执行此操作吗?

更新:

std::vector<int> idA={3, 7, 15, 16, 19, 30};
QSqlQuery qry(QString("SELECT name, memberType FROM members WHERE id IN (?%1)")
                .arg(QString(", ?").repeated(idA.size()-1)));
for(int i = 0; i < idA.size(); i++)
{
    int id2 = idA[i];
    qry.addBindValue(id2);
}
qry.exec();
model2->setQuery(qry);
ui->tableView_10->setModel(model2);

但是,还是没有输出到table。

在这种情况下,您必须使用的句子是 IN:

SELECT name, memberType FROM members WHERE id IN (2, 4, 5, 6)

在这种情况下,我们将使用字符串连接:

std::vector<int> idA = {3, 7, 15, 16, 19, 30};

QStringList ids_string;
for(const int & val : idA) 
    ids_string << QString::number(val);

QSqlQuery query(QString("SELECT name, memberType FROM members WHERE id IN (%1)")
                .arg(ids_string.join(",")));
model.setQuery(query);

示例:

#include <QApplication>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QTableView>

static bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if (!db.open()) {
        qDebug()<<"Unable to establish a database connection";
        return false;
    }
    QSqlQuery query;
    query.exec("CREATE TABLE IF NOT EXISTS members (id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "name VARCHAR(20), memberType VARCHAR(20))");
    for(int i=1; i<40; i++)
        query.exec(QString("insert into members(name, memberType) values('name%1', 'memberType%2')").arg(i).arg(i));
    return true;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    if(!createConnection())
        return -1;

    QTableView w;
    QSqlQueryModel model;
    std::vector<int> ids = {3, 7, 15, 16, 19, 30};
    QStringList ids_string;
    for(const int & val : ids) ids_string<<QString::number(val);
    QSqlQuery query(QString("SELECT name, memberType FROM members WHERE id IN (%1)")
                    .arg(ids_string.join(",")));
    model.setQuery(query);
    w.setModel(&model);
    w.show();
    return a.exec();
}

另一种解法:

int std::vector<int> idAr={3, 7, 15, 16, 19, 30};
int dateIndex = 6;
QSqlQuery query(QString("SELECT name, memberType FROM members WHERE id IN (?%1)")
                .arg(QString(", ?").repeated(idAr.size()-1)));
for(const int & id: idAr)
    query.addBindValue(id);
query.exec();