2

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 ???

Nejat
  • 31,784
  • 12
  • 106
  • 138
RicoRicochet
  • 2,249
  • 9
  • 28
  • 53
  • 5
    Please *do not* construct SQL statements using string concenation like that to avoid [SQL injection](http://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). – Frerich Raabe Dec 11 '14 at 08:35
  • seriously !!! its really informative. from now on i will look forward to avoid string concatenation in sql based apps. thanx for the link. – RicoRicochet Dec 11 '14 at 08:59

2 Answers2

4

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());
Nejat
  • 31,784
  • 12
  • 106
  • 138
  • your first solution to use .arg(ui->lineEdit->text()) worked for me... But i would request you to explain a little (briefly) about the usage of query.prepare and query.bindValue so that I can learn and implement later on. – RicoRicochet Dec 11 '14 at 08:51
  • 3
    @AmarjitBiswas Using `bindvalue` is more safe because it protects you from SQL injection. That's because you never pass values directly in the SQL statement when binding and the values are inserted after query compilation and before its execution. – Nejat Dec 11 '14 at 09:13
3

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);
thuga
  • 12,601
  • 42
  • 52