java – 选择特定字段不为NULL的所有记录

我有一个名为stars的MySQL表,其中一个字段是id_num,默认值为NULL.我想通过中的PreparedStatement选择id_num不为NULL的所有记录.

现在我正在尝试这个:

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

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

但它不起作用.

解决方法:

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

你不需要PreparedStatement.

从我的角度来看,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()));
上一篇:Sping POJO中如何添加验证规则和验证消息提示


下一篇:如何用jQuery获取选中行固定列的数据