You're re-using the same Statement
object to execute two queries. When the stmt
is used to execute the second query, the ResultSet
object returned by the previous statement is closed. Create two objects for each query.
Example:
Statement stmt = conn.createStatement();
Statement stmt1 = conn.createStatement();
...
ResultSet res = stmt.executeQuery(Query);
...
while(res.next()){
S_Code = res.getString("S_Code");
Query1 = "SELECT * From Subjects WHERE Prerequisite = '"+S_Code+"'";
res1 = stmt1.executeQuery(Query1); // use a separate statement
while(res1.next()){
DLM.addElement(res.getString("S_Code"));
}
}
This is explained in the following quote from the Statement
API docs:
By default, only one ResultSet
object per Statement
object can be open at the same time. Therefore, if the reading of one ResultSet
object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement
interface implicitly close a statment's current ResultSet
object if an open one exists.
Also it is strongly recommended to close the JDBC resources in the reverse order of their allocation, i.e.g you should close Statement
s then close the Connection
, and you should do this in a finally
block:
catch(SQLException e){
JOptionPane.showMessageDialog(null, e.toString());
} finally {
if(res != null) {
res.close();
}
if(res1 != null) {
res1.close();
}
if(stmt != null) {
stmt.close();
}
if(stmt1 != null) {
stmt1.close();
}
if(conn != null) {
conn.close();
}
}
If you're using Java 7, you can use a try-with-resources statement to automatically close these resources (without having to explicitly call the close()
method):
// try-with-resources statement declaring two resources
try(Connection conn = DriverManager.getConnection(url,username,password);
Statement stmt = conn.createStatement()) {
...
} catch(SQLException e){
JOptionPane.showMessageDialog(null, e.toString());
}
The try-with-resources will make sure to close the Statement
object, then the Connection
after they are used.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…