PDA

View Full Version : cannot get max(column) value in sql.



rahulvishwakarma
1st May 2020, 10:48
hi to all, I've Centos7.5 as client and centos6.10 as mysql server. i am building small project and here i want to get maximum value from billno ( bill number ). I've tried this code :-


int Sales::setmaxno()
{
QSqlQuery qury;
QString sql= "select max(billno) from tableSale";

query->prepare(sql);
if(query->exec() )
{
if(qury.next())
{
Sales::maxno = query->value(0).toInt();
return Sales::maxno;
}
}
else
{
QMessageBox::information(this, "Sales", "in else " + query->lastError().text() );
}
}


but this shows maxno = 0; always.
i think query "select max(billno) from tableSale"; is not selecting max of column.
how to get solved this problem.

Lesiok
1st May 2020, 12:28
First of all : this code should not compile.

rahulvishwakarma
1st May 2020, 14:23
you are right this code is not compiling but Why? please explain.

Lesiok
1st May 2020, 17:09
Because the return... line is missing before line 19. The compiler certainly gave the appropriate message.

d_stranz
1st May 2020, 22:42
Sales::maxno

Is "maxno" a static member variable of the Sales class? Why do you qualify it with the "Sales::" class scope? Look at your C++ textbook if you do not understand this.

rahulvishwakarma
2nd May 2020, 02:56
yes maxno is static member

ChrisW67
2nd May 2020, 08:40
int Sales::setmaxno()
{
QSqlQuery qury;
QString sql= "select max(billno) from tableSale";

query->prepare(sql);
if(query->exec() )
{
if(qury.next())
{
Sales::maxno = query->value(0).toInt();
return Sales::maxno;
}
}
else
{
QMessageBox::information(this, "Sales", "in else " + query->lastError().text() );
}
}


The variable "qury" at line 3 and 9 is not related to the undeclared (member?) variable "query" at lines 6, 7, and 11. You prepare() and exec() one QSqlQuery object then attempt to navigate another (invalid) object. If that worked, you would return value from the first QSqlQuery object, which is pointing at an invalid record. Since "qury" is not active the next() call will fail and your code (if it compiles at all) will return an undefined value because there is no other return statement.