Question

I am using the following approach to show the result of a select statement in the QTableView. How should I modify this code to show the result of two or more different select statements in the same QTableView?

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QString dbPath = "test1.db";
db.setDatabaseName(dbPath);

QSqlQueryModel *model = new CustomSqlModel();

QSqlQuery* query = new QSqlQuery(db);
query->prepare("SELECT * FROM MyTable");
query->exec();

model->setQuery(*query);
model->setHeaderData(0, Qt::Horizontal, "Col1");
model->setHeaderData(1, Qt::Horizontal, "Col2");
model->setHeaderData(2, Qt::Horizontal, "Col3");

QTableView* tableView = new QTableView();
tableView->setModel(model);

I need to append the data selected from the same table in another database test2.db to the data already shown in the tableView.

Was it helpful?

Solution

To append the result of one query to another, use a compound SELECT statement:

SELECT * FROM MyTable
UNION ALL
SELECT * FROM MyOtherTable

This requires that the subselects have the same number of columns.

If the other table is in another database, you must ATTACH it to the first one:

db.exec("ATTACH '/somewhere/else/test2.db' AS test2");
...
query->prepare("SELECT * FROM MyTable UNION ALL SELECT * FROM test2.MyTable");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top