Reputation: 2289
I am writing a GUI application which will perform select * from table_name from an oracle database and populate the result in a TableView Model. To take my query as an input for querying the database I have used---
QString MyQuery = ui->lineEdit->text();
QSqlQuery query(MyQuery,db);
and it works perfectly.
Now I want to optimize it by making the user type only the table_name as an input in the lineEdit. The program will perform select * from table_name on it by itself.
So I think I need to store "SELECT * FROM " in the QString variable and concatinate the input from lineEdit to it.
I am not much sure about the syntax of this concatination so both of my tries---
QString myquery;
strcat(myquery,"SELECT * FROM ");
strcat(myquery,ui->lineEdit );
and,
QString myquery = "SELECT * FROM " + ui-lineEdit->text();
have resulted in build errors. Any suggestions on how to perform the desired concatination ???
Upvotes: 2
Views: 513
Reputation: 32655
You can use QSqlTableModel
to show a table contents in a QTableView
:
QSqlTableModel * model = new QSqlTableModel(this,db);
model->setEditStrategy(QSqlTableModel::OnFieldChange);
model->setTable( "someTable" );
model->select();
ui->tableView->setModel( model );
But in case you want to use QSqlQuery
you can make the query like :
String myquery = QString("SELECT * FROM %1").arg(ui->lineEdit->text());
Or even better:
query.prepare("SELECT * FROM :tableName");
query.bindValue(":tableName", ui->lineEdit->text());
Upvotes: 4
Reputation: 12931
You can use QString::arg
to add arguments to a string.
For example:
QString input = ui->lineEdit->text();
QString myQUery = QString("SELECT * FROM %1").arg(input);
Upvotes: 3