我的DAO對象關閉連接
package com.myselect;
import java.sql.*;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataAccess {
Connection conn;
PreparedStatement pst;
ResultSet rs;
public DataAccess() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/db", "root", "root");
} catch (ClassNotFoundException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getAge(String name) {
String userage = null;
try {
pst = conn.prepareStatement("select age from mydb where name= ?");
pst.setString(1, name);
rs = pst.executeQuery();
while (rs.next()) {
userage = rs.getString("age");
System.out.println(userage);
}
} catch (Exception ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
return userage;
}
public int insertRecord(String name, int addage) {
int b = 0;
try {
pst = conn.prepareStatement("insert into mydb values(?,?)");
pst.setString(1, name);
pst.setInt(2, addage);
b = pst.executeUpdate();
} catch (Exception ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
return b;
}
}
我想關閉連接。我有幾個servlet調用了insertRecord
和getAge
方法。關閉我的連接的最佳方式是什麼?創建另一個方法並從insertRecord
和getAge
方法調用或在構造函數中?
爲什麼不能有2種方法,第一個打開JDBC資源,二來關閉它們? – Arvind
你順便提一下另一個主要問題:壓制異常並繼續,就像沒有任何異常發生一樣。這樣,servlet永遠不會意識到DAO調用是成功還是失敗,因此無法顯示錯誤頁面或消息。另請參閱此示例的另一個答案:http://stackoverflow.com/questions/5003142/jsp-using-mvc-and-jdbc – BalusC