Awa Melvine
Awa Melvine

Reputation: 4087

set prepared statement parameter where NOT NULL java

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.

Upvotes: 1

Views: 2432

Answers (2)

Ponni
Ponni

Reputation: 433

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

Use this not null for the respective column name role

Upvotes: -1

Nathan Hughes
Nathan Hughes

Reputation: 96385

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

Upvotes: 1

Related Questions