<分区>
我的 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;
}
}
我想关闭连接。我有几个调用 insertRecord
和 getAge
方法的 servlet。关闭连接的最佳方法是什么?创建另一个方法并从 insertRecord
和 getAge
方法或在构造函数中调用?