简体   繁体   English

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

[英]Select all records whose specific field is not NULL

I have a MySQL table named stars and one of its fields is id_num with default value NULL . 我有一个名为starsMySQL表,其中一个字段是id_num ,默认值为NULL I want to select all the records where id_num is not NULL through a PreparedStatement in . 我想通过PreparedStatement选择id_num 不为 NULL所有记录。

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. 但它不起作用。

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

you dont need a PreparedStatement for this. 你不需要PreparedStatement

From my point of view PreparedStatement should be used for SQL statements that take parameters. 从我的角度来看,PreparedStatement应该用于带参数的SQL语句。 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. 使用带参数的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()));

因为null不是值,所以它更多是SQL中的关键字,因此您必须将其硬编码到sql语句中

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

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 您可以在此处了解有关PreparedStatementResulSet的更多信息

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的主要功能是将参数插入到SQL语句中,在您的情况下,您不需要这样做,因为null不是一个参数,所以您可以清楚地做到:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM