简体   繁体   中英

Need to change ResultSet.getString(Value)-— conditionally

I have a query and a resultset

I do this

while (rs.next())
{    
    String string = rs.getString(ColumnName);

    if (String == "certainvalue")
    {  
        //perform action
    }else {
       //do nothing  
    }

My problem is that the if condition doesn't seem to be working.... even though I know "certainvalue" is in the result set, it never evaluates to true, and it never performs the action---- I am confused as to why that is...

is it because i am using a while loop?? or is it because resultsets are just wierd,, ,what is going on???

Java can't compare strings with ==. What you have to do is use the equals method of the String.

if (string.equals("certainvalue")) {
    perform action
}

String is an object. You can't do a comparison that way (you are trying to compare object reference).

If you are use java(aren't you?) try:

String string = rs.getString(columnName);
if (string.compareTo("anotherString") == 0){
}

You can use operator == just for primitive types (like int).

It looks you're using Java. In that case, the == operator compares if the two objects are the same, not if they represent the same value.

Rewrite the test :

if ("certainvalue".equals(string)) { doStuff(); }

(You might consider "a".equals(b) to be equivalent to b.equals("a"), but the first form protects you from a NullPointerException if there is no value for the row in the database.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM