My collegues passed me some code, and there are problems when I run the code. Here is some part of it
boolean purchased = false;
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
String sql = new StringBuilder().... // some query
rs = stmt.executeQuery(sql);
while (rs.next()) {
//some code
purchased = rs.getInt("purchased") == 1;
print(" purchased:" + purchased);
}
This always printed purchased as false. I changed that part to this:
while (rs.next()) {
//some code
if(rs.getInt("purchased") == 1) purchased = true;
print(" purchased:" + purchased);
}
Now it works perfectly.
note: my ResultSet can have only 1 record. And in DB purchased is bit type, so there can be no other values than 0/1.
What is the difference between those two ways of writing ? as I know both should work the same way.
What is the difference between those two ways of writing ? as I know both should work the same way.
No, definitely not. In your first piece of code, if rs.getInt("purchased")
returns a value other than 1, you assign a value of false
.
In your second piece of code, once purchased
has been set to true
, it stays true
for the rest of the loop.
So suppose your first row has a value of 1 for purchased
, and your second row has a value of 2, then in your first piece of code the variable will become true
then false
, but in your second piece of code the variable will be set to true
in the first iteration and then not changed in the second iteration.
See more on this question at Stackoverflow