Reputation:
int i = 0;
while (i < size) {
String s = username[i];
String sql4 = "select books1,books2 from " + uname + "a," + s + "b where " + uname + "a.books1=" + s + "b.books2";
ResultSet rs3 = con.createStatement().executeQuery(sql4);
System.out.println(sql4);
while (rs3.next()) {
count = rs3.getRow();
}
i++;
System.out.println(count);
After running this code the output should be 2,1,0,0
but instead output is 2,2,2,2
.that is sql query for i=0
Upvotes: 0
Views: 261
Reputation:
Use ResultSet.last()
instead of while loop. See following example.
count = rs3.last() ? rs3.getRow() : 0;
BAD PRACTICES OF CODE
Additionally it seems bad statements of your code. You are executing a query, inside a loop which make worse your program in performance. You can use SQL queries using COUNT
, JOIN
and another techniques to get your output easily and efficiently with less code.
Upvotes: 1
Reputation: 7919
Initialize the count
inside the loop
while (i < size) {
count=0;
//execute query
}
with your code its printing the previous value of count if no row found.
And instead of using while(rs3.next())
you can use select count(*) as cnt...
and use
if(rs3.next()){
count = rs3.getInt("cnt");
}
Upvotes: 0