MYSQL with Qt query and with var [solved]
-
wrote on 14 Mar 2014, 19:08 last edited by
Hello Forum,
i have a question about MYSQL Syntax in Qt. I have a table with the name “min5_1” an i have problems with the query.
The Code:
@ MainWindow main;
this->comboxLaden();
QString tableName = ui->tablesBox->currentText();
qDebug() << tableName;
QSqlQueryModel *model = new QSqlQueryModel();
QSqlQuery *qry = new QSqlQuery(main.mydb1);
qry->prepare("SELECT * FROM '"+tableName+"' ");
if(qry->exec())
{
qDebug() << "If schleife";
model->setQuery(*qry);
ui->anzeigenView->setModel(model);
}
else
qDebug() << "Else" << qry->exec();@The exec is always false. When i changed the var “tableName” to “min5_1” the query is true. What is wrong?
Alex
-
wrote on 14 Mar 2014, 22:08 last edited by
My first thought was a 'locked' database but hard coding the tablename shouldn't cause a difference.
Try adding qDebug() << qry.lastError();
after qry->prepare statement
and after qry->exec statement
See what pops up. Chasing these can be fun. -
wrote on 14 Mar 2014, 22:10 last edited by
Sorry qry->lastError();
-
wrote on 14 Mar 2014, 22:24 last edited by
The query->lastError(); is:
bq. QSqlError(1064, "QMYSQL: Unable to execute query", "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''min5_1'' at line 1")
And the Code is:
@MainWindow main;
this->comboxLaden();
QString tableName = ui->tablesBox->currentText();
QSqlQueryModel *model = new QSqlQueryModel();
QSqlQuery *qry = new QSqlQuery(main.mydb1);
qry->prepare("SELECT * FROM '"+tableName+"' ");
qry->exec();
qDebug() << qry->lastError();
model->setQuery(*qry);
ui->anzeigenView->setModel(model);@I´dont understand this. When i change the prepare with var to const string than it works correctly.
-
wrote on 14 Mar 2014, 22:38 last edited by
I think I would try:
QString sstr = ("SELECT * FROM '"+tableName+"' ");
qry->prepare(sstr); ...
You need to see what is actually passed to the prepare statement.
I also noticed in copying your line that there is a space after the final single quote. This may be the issue. -
wrote on 14 Mar 2014, 22:49 last edited by
Thank you. I have the right code:
@ MainWindow main;
this->comboxLaden();
QString tableName = ui->tablesBox->currentText();
QString stringQuery = "select * from "+tableName+"";
QSqlQueryModel *model = new QSqlQueryModel();
QSqlQuery *qry = new QSqlQuery(main.mydb1);
qry->prepare(stringQuery);
qry->exec();
qDebug() << stringQuery;
model->setQuery(*qry);
ui->anzeigenView->setModel(model);@It works correctly
-
wrote on 14 Mar 2014, 22:52 last edited by
And the other code:
@qry->prepare("select * from "+tableName+"");@
5/9