简体   繁体   English

需要更改ResultSet.getString(Value) - 有条件

[英]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... 我的问题是if条件似乎没有工作....即使我知道“certainvalue”在结果集中,它永远不会评估为true,它从不执行动作----我很困惑至于为什么那是......

is it because i am using a while loop?? 是因为我正在使用while循环? or is it because resultsets are just wierd,, ,what is going on??? 或者是因为结果集只是很奇怪,,,会发生什么?

Java can't compare strings with ==. Java无法将字符串与==进行比较。 What you have to do is use the equals method of the String. 你要做的是使用String的equals方法。

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

String is an object. String是一个对象。 You can't do a comparison that way (you are trying to compare object reference). 你不能这样做比较(你试图比较对象引用)。

If you are use java(aren't you?) try: 如果你使用java(不是吗?)尝试:

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

You can use operator == just for primitive types (like int). 您可以将operator ==仅用于基本类型(如int)。

It looks you're using Java. 它看起来你正在使用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.) (您可以将“a”.equals(b)视为等同于b.equals(“a”),但如果数据库中的行没有值,则第一种形式可以保护您免受NullPointerException的影响。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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