SELECT 1 FROM tasks WHERE `id`=? LIMIT 1
代码中的" ?" 表示需要查询的id号码,号码的输入可以直接在sql语句中修改,也可以创建preparedStatement,通过setLong加入。
try (
final Connection connection = createConnection();
final PreparedStatement selectPreparedStatement = connection.prepareStatement("SELECT 1 FROM tasks WHERE `id`=? LIMIT 1");
) {
selectPreparedStatement.setLong(1, id);
final ResultSet resultSet = selectPreparedStatement.executeQuery();
if (!resultSet.next()) {
System.out.println("id does not exist");
return;
}
将查询结果放入的resultSet中,判断resultSet是否为空。如果为空,则代表前面的查询语句没有查询出结果,因为id不存在,所以查询语句没有返回值。如果resultSet不为空,则表示前面的语句查询出了结果,结果中包含一个长度为1的查询结果,表示id存在。