O
O
Oleg Seledets2019-01-09 09:17:40
Qt
Oleg Seledets, 2019-01-09 09:17:40

How to extract all values ​​from QTableWidget?

Hello,
there is a tableWidget in it is always a different number of rows, but one column.
Is there any way to substitute all the Values ​​from this table into the SQL query:

SELECT *
FROM Universities
WHERE Location IN ('Novosibirsk', 'Perm')

In brackets instead of Novosibirsk and Perm?
Do something with a loop extracting values ​​one by one?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-01-09
@oleja1ee7

UPD
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "memdb");
db.setDatabaseName(":memory:");

if (!db.open())
{
    qDebug() << db.lastError().text();
    // std::exit(1);
}

QSqlQuery q("", db);
q.exec("create table Universities (id integer primary key, Location varchar, Population integer)");
q.exec("insert into Universities values (0, 'MSK', 12000000)");
q.exec("insert into Universities values (1, 'NSK', 1600000)");
q.exec("insert into Universities values (2, 'SPB', 6000000)");
q.exec("insert into Universities values (3, 'PRM', 1000000)");

int sz = ui->tableWidget->rowCount();

QString queryString = "SELECT * FROM Universities WHERE Location IN (";
for(int i = 0; i < sz; ++i)
{
    queryString += "?,";
}
queryString.back() = ')';

QSqlQuery query(queryString, db);

for(int i = 0; i < sz; ++i)
{
  query.bindValue(i, ui->tableWidget->item(i, 0)->text());
}

if (!query.exec())
{
  qDebug() << query.lastError().text();
  // std::exit(1);
}

while(query.next())
{
  qDebug() << query.value(0).toInt() << " "
           << query.value(1).toString() << " "
           << query.value(2).toInt() << "\n";
}

old
doc.qt.io/qt-5/qsqlquery.html#addBindValue
QSqlQuery query;
query.prepare("SELECT * FROM Universities WHERE Location IN (?)");

int sz = ui->tableWidget->rowCount();

QVariantList values;
for(int i = 0; i < sz; ++i)
{
  values << ui->tableWidget->item(i, 0)->text();
}
    
query.addBindValue(values);
if (!query.execBatch())
{
  qDebug() << query.lastError();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question