我正在尝试获取ResultSet
的第一个元素。为什么我收到此错误
public ResultSet executeSearch(String q){
openConnection();
ResultSet resultSet = null;
try{
Statement statement = connection.createStatement();
resultSet = statement.executeQuery(q);
closeConnection();
return resultSet;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
finally {
closeConnection();
}
return resultSet;
}
public int getAddressID(String city) throws SQLException{
String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE city =" + "\'"+ city + "\';";
System.out.println(q);
ResultSet rs = executeSearch(q);
int i = 0;
if (rs.next()){
i = rs.getInt(1);
};
return i;
}
答案 0 :(得分:1)
您收到此错误是因为您尝试在关闭之后阅读ResultSet
,这是被禁止的。
您需要在方法ResultSet
中关闭您的连接(以及getAddressID
},而不是下一个:
public ResultSet executeSearch(String q){
openConnection();
try {
return connection.createStatement().executeQuery(q);
} catch (Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
return null;
}
public int getAddressID(String city) throws SQLException{
...
try (ResultSet rs = executeSearch(q)) {
...
} finally {
closeConnection();
}
return i;
}