PDA

View Full Version : How to get value from a query statement ?



hohoanganh205
5th January 2012, 11:44
I exec a statement SQL in MYSQL Workbench and result is: 2 ; pic:

7240

But in C++ QT I do not know how to get the value like MYSQL, I try this code and result not is: 2



void QuanLyDaiLy::on_pushButton_clicked()
{
QSqlQuery *qry = new QSqlQuery();
qry->prepare("select count(MaDaiLy) as SoDaiLyTrongQuan from DaiLy, Quan where DaiLy.Quan_TenQuan = Quan.TenQuan and Quan.TenQuan = 'Quan 10'");
qry->exec();

QMessageBox::information(this,"result",QString::number(qry->size()));
}


7241

what can I use to QString::number(qry->????????) to get the value ?

Thanks for help .

Lykurg
5th January 2012, 12:00
See QSqlQuery::value().

hohoanganh205
5th January 2012, 14:11
Thanks you very much, I done.




QSqlQuery q("select count(MaDaiLy) as SoDaiLyTrongQuan from DaiLy, Quan where DaiLy.Quan_TenQuan = Quan.TenQuan and Quan.TenQuan = '" + ui.cbTenQuan->currentText() + "'");
QSqlRecord rec = q.record();
int nameCol = rec.indexOf("SoDaiLyTrongQuan"); // index of the field "name"
q.next();
int SoDLHienCoTrongQuan = q.value(nameCol).toInt();



the result is return: 2

Lykurg
5th January 2012, 14:23
Hi, since you only query one "field" the index is 0. Thus you can simplify your code:
QSqlQuery q("select count(MaDaiLy) from DaiLy, Quan where DaiLy.Quan_TenQuan = Quan.TenQuan and Quan.TenQuan = '" + ui.cbTenQuan->currentText() + "'");
q.next();
int SoDLHienCoTrongQuan = q.value(0).toInt();
Further have a look at QSqlQuery::bindValue().