Нулевая проверка не может быть выполнена с = null
, вместо этого она должна быть сделана так:
select * from test5 where id2 is null
Если попытаться сделать это с установкой нуля, через
ps.setNull(1, java.sql.Types.BIGINT);
выдает исключение из драйвера JDBC:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
Position: 34
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:106)
Одним из возможных решений является сделать конкретный запрос в этом случае:
select * from test5 where id2 is null
Тест
Здесь автономная Java-программа с JDBC:
import java.util.Properties;
import java.sql.*;
public class Main {
public static void main(String[] args) {
try {
Connection connection = createConnection();
try (connection) {
/*
PreparedStatement ps = connection.prepareStatement(
"select * from test5 where id2 is ?");
ps.setNull(1, java.sql.Types.BIGINT);
*/
PreparedStatement ps = connection.prepareStatement(
"select * from test5 where id2 is null");
try (ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
int id1 = rs.getInt(1);
System.out.println("found entry with id1='" + id1 + "'");
}
}
ps.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Connection createConnection()
throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost/stephan";
Properties props = new Properties();
props.setProperty("user", "stephan");
props.setProperty("password", "secret");
return DriverManager.getConnection(url, props);
}
}
Если содержимое таблицы test5 выглядит следующим образом:
stephan=# select * from test5;
id1 | id2 | id3 | id4 | id5 | id6 | id7 | id8 | id9
-----+-----+-----+-----+-----+-----+-----+-----+-----
4 | | | | | | | |
(1 row)
тогда вывод на консоль отладки выглядит так:
found entry with id1='4'