MYSQL with Qt query and with var [solved]
-
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
-
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.
-
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. -
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