-3

I inserted one column in sql with null value from java.while retrieving back it is not working with null.i also checked with string.length().But when i printed the value in System.out. the value is showing as null (just null).when i checked it with condition it is not entering into loop.

String id ="1234"; 
            String name="pratap";
            String gender=null;
            String email=null;
String service="GOOGLE";
        log.info(id+name+gender+email) //output is 1234pratapnullnull   

String insert = "INSERT INTO oauthuser VALUES('"+id+"','"+name+"','"+gender+"','"+email+"','"+service"')";

In the retrieval

query ="Select * FROM oauthuser where id="+"'"+id+"'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
  while(rs.next())
  {
 id=rs.getString(1);
 name=rs.getString(2);
 gender=rs.getString(3);
 email=rs.getString(4);
service_provider_name=rs.getString(5);
System.out.println(gender+email+name);//output is nullnullpratap

  } 

if(gender!="male" && gender!="female")
 System.out.println("it is printing");
  if(gender==null)
      System.out.println("it is not printing");
con.close();
Pratap M
  • 1,059
  • 3
  • 21
  • 31

3 Answers3

2

From your somewhat cryptic description of the problem I suspect that you may have inserted the string "null" rather than the SQL NULL value. The two are not the same (very different, in fact).

edit Having reviewed the code, this is exactly what happens. Take, for example, gender:

String gender = null;
...'"+gender+"',...

The above converts it to 'null' (i.e. the SQL string "null"), and inserts that into the database.

My basic advice would be to read up on PreparedStatement and use that instead of building the SQL query bit by bit as you're doing right now.

Finally, the following is broken:

if(gender!="male" && gender!="female")

This should be

if(!gender.equals("male") && !gender.equals("female"))
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Maybe your value is not null but "null" string? Start your application in debug, put break point and check it.

alexey28
  • 5,170
  • 1
  • 20
  • 25
1

you can try "null" instead of NULL , but better to show us the code

after your update

remove + sign from your query like this

String id ="1234"; 
            String name="pratap";
            String gender="null";
            String email="null";
String service="GOOGLE";
        log.info(id+name+gender+email) //output is 1234pratapnullnull   

String insert = "INSERT INTO oauthuser VALUES('"id"','"name"','"gender"','"email"','"service"')"

and when you select , modify like this

if(gender.equals("null"))
      System.out.println("it is not printing");
Community
  • 1
  • 1
William Kinaan
  • 28,059
  • 20
  • 85
  • 118