Select all records whose specific field is not NULL

I have a table MySQLwith a name stars, and one of its fields has a id_numdefault value NULL. I want to select all entries where id_num not NULL through PreparedStatementin java .

Now I am trying to do 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 does not work.

+4
source share
4 answers
private final String idStarsSQL = "select * from `stars` where id_num is not NULL";

you do not need PreparedStatementto do this.

PreparedStatement SQL, . SQL, , , , .

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()));
+2

null , SQL, sql

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

:

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");
}

PreparedStatement ResulSet

+1

readyStatement - SQL, , null , :

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

Source: https://habr.com/ru/post/1671972/


All Articles