Java.sql.ResultSet bug for rs.next() - java

The SQL code works and next() function outputs true or false but is not accepted by the if (condition).
boolean status = res.next();
if (res.next()) {
System.out.println("first");
}
if (status) {
System.out.println("second");
}
The code above has the same semantics but the one using the method next() doesn’t work.

If there is only one record in the resultset, status will be true but the next attempt of res.next() will return false. Thus, the following code will output only second.
boolean status = res.next();
if (res.next()) {
System.out.println("first");
}
if (status) {
System.out.println("second");
}
If there are two records in the resultset, you will get both, first and second as the output.
To summarize,
Output when there is only one record in the resultset
second
Output when there are two records in the resultset
first
second

What you did making the result set to move to the second row because you call next() twice
, You can check this one:
if (res.next()) {
System.out.println(“first”);
} else {
System.out.println(“second”);
}

Related

How to get multiple lines from mysql

I'm trying to fetch from mysql table multiple lines data, for example:
1 car
2 shop
3 dress
But for now it's only fetch the first line.
My code so far:
case "2":
ResultSet rsl2 = stmt.executeQuery("SELECT payments FROM payment;" );
while(rsl2.next()) {
String sqlRes = rsl2.getString("payments");
System.out.println(sqlRes);
if (sqlRes != null) {
System.out.println("OK");
return sqlRes;
}
}
You may either append all your data to the sqlRes variable
sqlRes += rsl2.getString("payments");
and change your if statement to
if (sqlRes == null)
return sqlRes;
or place your return statement after the while loop. Either way, you should append the data in the sqlRes variable if you finally want the returned value to hold all the values in your DB.

java jdbc executeQuery() working but execute() not (multiple resultsets) [duplicate]

I'm calling a Sybase stored procedure that returns multiple resultsets through JDBC.
I need to get a specific result set that has a column named "Result"
This is my code :
CallableStatement cs = conn.prepareCall(sqlCall);
cs.registerOutParameter(1, Types.VARCHAR);
cs.execute();
ResultSet rs=null;
int count = 1;
boolean flag = true;
while (count < 20000 && flag == true) {
cs.getMoreResults();
rs = cs.getResultSet();
if (rs != null) {
ResultSetMetaData resultSetMetaData = rs.getMetaData();
int columnsCount = resultSetMetaData.getColumnCount();
if (resultSetMetaData.getColumnName(1).equals("Result")) {
// action code resultset found
flag = false;
// loop on the resultset and add the elements returned to an array list
while (rs.next()) {
int x = 1;
while (x <= columnsCount) {
result.add(rs.getString(x));
x++;
}
}
result.add(0, cs.getString(1));
}
}
count++;
}
What happens here is that cs.getMoreResults returns a lot of null resultsets till it reaches the target one. I can't use cs.getMoreResults as loop condition because it returns false for null resultsets.
I put a fixed number to end the loop in condition the wanted result set wasn't returned to prevent it from going into infinite loop. It worked fine but I don't think this is right.
I think the null resultsets returned from the assignment in Sybase select #variable = value
Has anyone faced this before?
You are misinterpreting the return value of getMoreResults(). You are also ignoring the return value of execute(), this method returns a boolean indicating the type of the first result:
true: result is a ResultSet
false : result is an update count
If the result is true, then you use getResultSet() to retrieve the ResultSet, otherwise getUpdateCount() to retrieve the update count. If the update count is -1 it means there are no more results. Note that the update count will also be -1 when the current result is a ResultSet. It is also good to know that getResultSet() should return null if there are no more results or if the result is an update count (this last condition is why you get so many null values).
Now if you want to retrieve more results, you call getMoreResults() (or its brother accepting an int parameter). The return value of boolean has the same meaning as that of execute(), so false does not mean there are no more results!
There are only no more results if the getMoreResults() returns false and getUpdateCount() returns -1 (as also documented in the Javadoc)
Essentially this means that if you want to correctly process all results you need to do something like below:
boolean result = stmt.execute(...);
while(true) {
if (result) {
ResultSet rs = stmt.getResultSet();
// Do something with resultset ...
} else {
int updateCount = stmt.getUpdateCount();
if (updateCount == -1) {
// no more results
break;
}
// Do something with update count ...
}
result = stmt.getMoreResults();
}
My guess is that you are getting a lot of update counts before you get the actual ResultSet.
I am not really familiar with Sybase, but its cousin SQL Server has the 'annoying' feature to return update counts from stored procedures if you don't explicitly put SET NOCOUNT ON; at the start of the stored procedure.
NOTE: Part of this answer is based on my answer to Execute “sp_msforeachdb” in a Java application

Return statement function in if conodition

In my code:
if (id.isEmpty() || name.isEmpty()) {
warlbl.setText("Warning, Empty ID or Name Fields");
return;
}
id and name are String that give from JTextFields ,
Is necessary use return; in here or Not?
Yes, it can be:
if (...) {
...
return;
}
// nothing at this point will be reached if the if-statement is entered
vs.
if (...) {
...
}
// code here will still be reached!
return exits the current method you are "in".
Of yource it is not necessary but maybe you want to exit the method if id.isEmpty() and name.isEmpty(). So no and yes. It is not neccassary but you may want to return
You can use return to break out of a method, continue to skip a loop or a break to break out of a block.
Often there are 2 ways:
public void test() {
if (!statement) {
// to something if statement is false
} else {
//we failed, maybe print error
}
}
or:
public void test() {
if (statement) {
//we failed, maybe print error
return;
}
//do something if statment is false
}
But this is more a kind of "style". Mostly I prefere the second way, just because it's less spagetti :P
Keep in mind. If your return statement would be the last statment executed it's redundant.
Java reference:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Null resultsets when calling Sybase stored procedure through JDBC

I'm calling a Sybase stored procedure that returns multiple resultsets through JDBC.
I need to get a specific result set that has a column named "Result"
This is my code :
CallableStatement cs = conn.prepareCall(sqlCall);
cs.registerOutParameter(1, Types.VARCHAR);
cs.execute();
ResultSet rs=null;
int count = 1;
boolean flag = true;
while (count < 20000 && flag == true) {
cs.getMoreResults();
rs = cs.getResultSet();
if (rs != null) {
ResultSetMetaData resultSetMetaData = rs.getMetaData();
int columnsCount = resultSetMetaData.getColumnCount();
if (resultSetMetaData.getColumnName(1).equals("Result")) {
// action code resultset found
flag = false;
// loop on the resultset and add the elements returned to an array list
while (rs.next()) {
int x = 1;
while (x <= columnsCount) {
result.add(rs.getString(x));
x++;
}
}
result.add(0, cs.getString(1));
}
}
count++;
}
What happens here is that cs.getMoreResults returns a lot of null resultsets till it reaches the target one. I can't use cs.getMoreResults as loop condition because it returns false for null resultsets.
I put a fixed number to end the loop in condition the wanted result set wasn't returned to prevent it from going into infinite loop. It worked fine but I don't think this is right.
I think the null resultsets returned from the assignment in Sybase select #variable = value
Has anyone faced this before?
You are misinterpreting the return value of getMoreResults(). You are also ignoring the return value of execute(), this method returns a boolean indicating the type of the first result:
true: result is a ResultSet
false : result is an update count
If the result is true, then you use getResultSet() to retrieve the ResultSet, otherwise getUpdateCount() to retrieve the update count. If the update count is -1 it means there are no more results. Note that the update count will also be -1 when the current result is a ResultSet. It is also good to know that getResultSet() should return null if there are no more results or if the result is an update count (this last condition is why you get so many null values).
Now if you want to retrieve more results, you call getMoreResults() (or its brother accepting an int parameter). The return value of boolean has the same meaning as that of execute(), so false does not mean there are no more results!
There are only no more results if the getMoreResults() returns false and getUpdateCount() returns -1 (as also documented in the Javadoc)
Essentially this means that if you want to correctly process all results you need to do something like below:
boolean result = stmt.execute(...);
while(true) {
if (result) {
ResultSet rs = stmt.getResultSet();
// Do something with resultset ...
} else {
int updateCount = stmt.getUpdateCount();
if (updateCount == -1) {
// no more results
break;
}
// Do something with update count ...
}
result = stmt.getMoreResults();
}
My guess is that you are getting a lot of update counts before you get the actual ResultSet.
I am not really familiar with Sybase, but its cousin SQL Server has the 'annoying' feature to return update counts from stored procedures if you don't explicitly put SET NOCOUNT ON; at the start of the stored procedure.
NOTE: Part of this answer is based on my answer to Execute “sp_msforeachdb” in a Java application

Check to see if ResultSet is Null if not then get int

I want to be able to get check to see if there is a result in my resultset. Todo this i would execute:
if(rs.next()){
boolean = true;
}
However i want to check to see if the value is in the database if so retrieve it:
while(rs.next())
id = rs.getInt("id);
How would i go about combining the two? I want -2 to be returned if the resultset is empty.
Thanks in Advance,
Dean
id = rs.next() ? rs.getInt("id") : -2;
like that?
Just use an if-else:
if (resultSet.next()) {
return resultSet.getInt("id");
} else {
return -2;
}
Also see this answer for more hints how to handle existence, zero/one, zero/more results.

Categories