日期:2014-05-18  浏览次数:20710 次

连接池close以后,不能再次连接
我用的是tomcat6,其中有一个更新数据的页面,只能更新一次,返回后便不会再次更新.代码如下:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.wm.pool.DatabaseConn;

public class ContactServlet extends HttpServlet {
private Connection con;

// 执行GET请求,修改数据库中的个人用户信息
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
.
.
.
.
PreparedStatement pstmt = null;

try {
pstmt = con.PrepareStatement("UPDATE usersinfo SET TrueName=?,Sex=? where UserName=?");
pstmt.setString(1, trueName);
pstmt.setInt(2, Integer.parseInt(request.getParameter("sex"))); 
pstmt.execute();
} catch (Exception e) {
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException ex2) {
ex2.printStackTrace();
}
}

if (con != null) {
try {
con.close();
} catch (SQLException ex3) {
ex3.printStackTrace();
}
}
}
response.sendRedirect("autoJump.jsp#1");
}

// 执行doGet一样的操作
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

// 创建一个Connection对象,用于执行数据库操作
public ContactServlet() {
try {
con = DatabaseConn.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
}

这是为什么?查了好久都没有查到.
如果将finally {}去掉,也就是不加上con.close(),便不会有问题...

------解决方案--------------------
在Servlet的Init函数中写相关获取连接的方法试试,在构造函数中写会出这种问题的。
------解决方案--------------------
servlet只初始化一次,第一次你获得了连接,第二次request的时候servlet不会在被初始化了,所以你根本没有获得链接

在doGet里面再获得一次链接吧
------解决方案--------------------
pstmt = con.PrepareStatement("UPDATE usersinfo SET TrueName=?,Sex=? where UserName=?");
pstmt.setString(1, trueName);
pstmt.setInt(2, Integer.parseInt(request.getParameter("sex"))); 
pstmt.execute(); 
这段是不是有点问题啊?
另外,建议你把数据库连接放到doGet里面,而不是一个servlet只用一个Connection
------解决方案--------------------
写一个连接池,做一个getConnection方法,每次获取一个就ok啦!
------解决方案--------------------
在pstmt = con.PrepareStatement之前,要重新获取连接
conn = your_datasource.getConnection();
你每次关闭以后,conn就被放回到连接池,所以你要用的时候,就必须要从连接池中重新取得