我仍在研究提到
here的同样问题.它似乎工作正常,特别是在创建如下所示的AbstractModel类之后:
public abstract class AbstractModel {
protected static Connection myConnection = SingletonConnection.instance().establishConnection();
protected static Statement stmt;
protected static ResultSet rs;
protected boolean loginCheck; // if userId and userLoginHistoryId are valid - true, else false
protected boolean userLoggedIn; // if user is already logged in - true, else false
public AbstractModel (int userId, Long userLoginHistoryId){
createConnection(); // establish connection
loginCheck = false;
userLoggedIn = false;
if (userId == 0 && userLoginHistoryId == 0){ // special case for login
loginCheck = true; // 0, 0, false, false
userLoggedIn = false; // set loginCheck to true, userLogged in to false
} else {
userLoggedIn = true;
try{
String query = "select \"user_login_session_check\"(" + userId + ", " + userLoginHistoryId + ");";
System.out.println("query: " + query);
stmt = myConnection.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()){
loginCheck = rs.getBoolean(1);
}
} catch (SQLException e){
System.out.println("SQL Exception: ");
e.printStackTrace();
}
}
}
// close connection
public void closeConnection(){
try{
myConnection.close();
} catch (SQLException e){
System.out.println("SQL Exception: ");
e.printStackTrace();
}
}
// establish connection
public void createConnection(){
myConnection = SingletonConnection.instance().establishConnection();
}
// login session check
public boolean expiredLoginCheck (){
if (loginCheck == false && userLoggedIn == true){
closeConnection();
return false;
} else {
return true;
}
}
}
我已经在上面问题的链接中发布了存储过程和Singleton Pattern实现.
我的印象是,在每次单个数据事务之后,我不需要关闭与数据库的连接,因为它只会减慢应用程序的速度.我正在为我正在构建的这个系统寻找大约30个用户,因此性能和可用性非常重要.
延长至少3-4次数据交易的连接是否正确?例如.验证检查某些表单的用户输入,或类似于谷歌的自动建议…这些都是基于用户输入的单独存储的函数调用.我可以使用一个连接实例,而不是在每次数据事务后连接和断开连接吗?哪个更有效率?
如果我的假设是正确的(使用一个连接实例更有效),那么应该在控制器中处理连接的打开和关闭,这就是我创建createConnection()和closeConnection()方法的原因.
谢谢.