1

To perform an sql query in java using prepared statement, I know that you do it like this:

Connection con=UserModel.getConnection();  
String sql = "UPDATE users SET firstname=?,lastname=? WHERE id=?";
PreparedStatement ps=con.prepareStatement(sql); 

ps.setString(1,u.getFirstname());  
ps.setString(2,u.getLastname());  
ps.setString(3,u.getId());

Where the first parameters in the setString method represent the order of the values to go into the sql statement in places where you have the ? sign.

Now what I want to do is select from users table where role is NOT NULL. Something like this:

Connection con = UserModel.getConnection();  
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE role=?");
ps.setString(1,not_null); // ***here***

How do I select where role is not null? That is my question.

Awa Melvine
  • 3,797
  • 8
  • 34
  • 47

2 Answers2

1

Use sql with a where clause of:

where role is not null 

Using = to compare something to null won’t work. The setNull on PreparedStatement - see JDBC:Inserting null to Integer column - substitutes the null, but that doesn’t help here because the where clause condition is always false. For why, see Why does NULL = NULL evaluate to false in SQL server

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
-1

Connection con = UserModel.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE role is NOT NULL"); ps.executeQuery();

Ponni
  • 433
  • 5
  • 17