-1

I got a database table having a nullable varchar2 column. The value is "NULL" as string. When trying to handle the result-set I'm facing the problem that the string "NULL" doesn't match anything.

I'm using an Oracle 11g XE database and ojdbc6.jar libraries.

What am I doing wrong?


Following an example for reproducing the behaviour:

Sql:

CREATE TABLE jtest (
  ID NUMBER(3) PRIMARY KEY,
  TEXT VARCHAR2(30) NULL
);
INSERT INTO jtest VALUES (1, 'Test1');
INSERT INTO jtest VALUES (2, 'NULL');

nullstring.java

public class nullstring {

final static String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";  
final static String DB_URL      = "jdbc:oracle:thin:@myhost:1521:xe";
final static String DB_USER     = "myuser";
final static String DB_PASS     = "myuserpw";

public static void main(String[] args) throws ClassNotFoundException, SQLException, UnsupportedEncodingException {
    Class.forName(JDBC_DRIVER);

    Connection hDB = null;
    hDB = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);

    String sCelldata = "";
    Statement oStatement = null;

    oStatement = hDB.createStatement();
    ResultSet oResult = oStatement.executeQuery("SELECT id, text FROM jtest");

    while (oResult.next()) {
        for (int i = 1 ; i < (oResult.getMetaData().getColumnCount() + 1); i++) {
            String test = "NULL";
            if ( test == "NULL" ) {
                System.out.println(">> 1111111111111111111111111111111");
            }
            if ( oResult.getString(i) == "NULL" ) {
                System.out.println(">> 2222222222222222222222222222222");
            }
            sCelldata = URLDecoder.decode(oResult.getString(i), "UTF-8"); 
            if ( sCelldata == "NULL" ) {
                System.out.println(">> 3333333333333333333333333333333");
            }

            System.out.println("> [" + i + "] " + sCelldata);
            sCelldata = ""; 
        }
    }

    hDB.close();
}
}

Output:

>> 1111111111111111111111111111111
> [1] 1
>> 1111111111111111111111111111111
> [2] Test1
>> 1111111111111111111111111111111
> [1] 2
>> 1111111111111111111111111111111
> [2] NULL
>> 1111111111111111111111111111111
Yaerox
  • 608
  • 2
  • 11
  • 27

1 Answers1

-1

String comparisons should be done using equals. you are now comparing the memory locations. ex:

String test = value_from_db;
if (test == null || "null".equalsIgnoreCase(test)) {
    System.out.println("test is null, or contains the value 'null'");
}
epoch
  • 16,396
  • 4
  • 43
  • 71
  • Duplicate questions should be handled by closing them, not by answering them over and over again. – Tom Mar 20 '17 at 14:44