No data from mysql database returned.
-
wrote on 14 Feb 2016, 20:04 last edited by cbrwx
Hello,
Having some issues with a little program im making, where i am trying to show the data from a table in a database, however the data does not show, only the tables. (mysql)
The code for the query, let me know what more is needed to tell me how much of a noob i am :p
Thanks if anyone have the time for this issue.
void Regnskap_prog::on_pushButton_loadtable_clicked()
{Login conn; QSqlQueryModel * modal=new QSqlQueryModel(); conn.connOpen(); QSqlQuery* qry=new QSqlQuery(conn.the_db); qry->prepare("select * from tablename ORDER BY id DESC");
// have tried even the simplest of queries, but still does
// not return any data to my tableview, just the structure of the tables.qry->exec(); modal->setQuery(*qry); ui->tableView_2->setModel(modal); conn.connClose(); qDebug() <<(modal->rowCount());
}
...and from the header file
public:
QSqlDatabase the_db;
void connClose()
{
the_db.close();
the_db.removeDatabase(QSqlDatabase::defaultConnection);}
bool connOpen()
{
the_db=QSqlDatabase::addDatabase("QMYSQL");the_db.setHostName("localhost/url"); the_db.setDatabaseName("dbname"); the_db.setUserName("name"); the_db.setPassword("password"); // bool ok = the_db.open();
if(!the_db.open())
{
qDebug()<<("Failed to connect to database.");
return false;
}
else
{
qDebug()<<("Connected to database");
return true;
}
} -
Hi and welcome to devnet,
You're closing the database connection immediately after you set the query so it's very likely that not all data (if any) could be retrieved.
You're also creating a leak. There's no need to create a QSqlQuery on the heap.
If you have a doubt about a query, check that it actually ran properly with QSqlQueryModel::lastError.
Hope it helps
-
wrote on 14 Feb 2016, 23:24 last edited by
thank you for your reply and help!
how do you suggest i close the database properly and in time for the data to be retrieved?
-
What reason do you have to close that connection ?
If you really need to, you have to at least ensure all data has arrived and only then close it. But depending on what your application will be doing, you'll have to open that connection again prior to any query run. So is it really worth to open/close/open again ?
-
wrote on 14 Feb 2016, 23:29 last edited by
yea probably a good point, btw it works when i remove the close, thanks for your help, problem solved :)
-
You're welcome !
Since you have it working now, please mark the thread as solved using the "Topic Tool" button so that other forum users may know a solution has been found :)
Also, while browsing the forum, consider up-voting answers that helped you. It will make them easier to find by other users :)
-
wrote on 15 Feb 2016, 00:13 last edited by
done and done!
1/7