4

I have a MySQL table named stars and one of its fields is id_num with default value NULL. I want to select all the records where id_num is not NULL through a PreparedStatement in .

Right now I am trying this :

private final String idStarsSQL = "select * from `stars` where id_num is not ?";
...

preparedStatement = (PreparedStatement) connection.prepareStatement(idStarsSQL);
preparedStatement.setString(1, NULL);
set = preparedStatement.executeQuery();

but it is not working.

Marievi
  • 4,951
  • 1
  • 16
  • 33

4 Answers4

2
private final String idStarsSQL = "select * from `stars` where id_num is not NULL";

you dont need a PreparedStatement for this.

From my point of view PreparedStatement should be used for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.

Statement statement = con.createStatement();
    ResultSet result = statement.executeQuery("select username, age, nickname from user where nickname is not NULL");
    List<User> allUserNullNickname = new ArrayList<>();
    while(result.next()){
        User user = new User();
        user.setUsername(result.getString("username"));
        user.setAge(result.getInt("age"));
        allUserNullNickname.add(user);
    }
    System.out.println("All user without nickname:");
    allUserNullNickname.stream().forEach(user -> System.out.println("username: "+user.getUsername()+" Age: "+user.getAge()));
nano_nano
  • 12,351
  • 8
  • 55
  • 83
1

Because null is a not a value, it more of a keyword in SQL, so you have to hard code it into your sql statement

private final String idStarsSQL = "select * from `stars` where id_num is not NULL";
Mehdi
  • 582
  • 4
  • 14
1

You can use :

PreparedStatement preparedStatement = 
            connection.prepareStatement("select * from `stars` where id_num is not NULL");
ResultSet result = preparedStatement.executeQuery();

while (result.next()) {
    result.getString("attribute1");
    result.getString("attribute2");
}

You can learn more here about PreparedStatement and about ResulSet

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

The preparedStatement's primary feature is to insert parameters into the SQL statement and in your case you dont need to do this because null is not a param so you can clearly do :

PreparedStatement myRequest= 
            connection.prepareStatement("select * from `stars` where id_num is not NULL");
ResultSet myResult= preparedStatement.executeQuery();
Younes Ouchala
  • 300
  • 1
  • 4
  • 15