使用finally关键词去关闭数据库连接
public void addStudent(Student theStudent) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
try {
// get db connection
myConn = dataSource.getConnection();
// create sql for insert
String sql = "insert into student "
+ "(first_name, last_name, email) "
+ "values (?, ?, ?)";
myStmt = myConn.prepareStatement(sql);
// set the param values for the student
myStmt.setString(1, theStudent.getFirstName());
myStmt.setString(2, theStudent.getLastName());
myStmt.setString(3, theStudent.getEmail());
// execute sql insert
myStmt.execute();
}
finally {
// clean up JDBC objects
close(myConn, myStmt, null);
}
}
private void close(Connection myConn, Statement myStmt, ResultSet myRs) {
try {
if (myRs != null) {
myRs.close();
}
if (myStmt != null) {
myStmt.close();
}
if (myConn != null) {
myConn.close(); // doesn't really close it ... just puts back in connection pool
}
}
catch (Exception exc) {
exc.printStackTrace();
}
}