日期:2014-05-18 浏览次数:20912 次
import java.sql.Connection; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class ConnectionFactory { private static DataSource ds = null; private ConnectionFactory() { } static { try { Context initCtx = new InitialContext(); Context ctx = (Context) initCtx.lookup("java:comp/env"); ds = (DataSource)ctx.lookup("jdbc/main"); }catch(NamingException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return ds.getConnection(); } } import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcUtil { public static void close(ResultSet rs, Statement st, Connection con) { close(rs); close(st); close(con); } public static void close(ResultSet rs) { if(rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * PreparedStatement, CallableStatement 都是 Statement 的子类,可以共用这个方法 * @param st */ public static void close(Statement st) { if(st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Connection con) { if(con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } private JdbcUtil() { } }
------解决方案--------------------
看样子是高并发时候多线程访问关闭连接问题,可以试用threadLocal取con关闭
而且关con可以在过滤器关,你每个方法close下,万一忘记不就资源没关么~
public class DBUtil { private static final ThreadLocal threadLocal = new ThreadLocal(); private DBUtil() { } /** * 获取当前数据库连接 * * @return * @throws Exception */ public synchronized static Connection getCurrentConnection() throws Exception { Connection conn = (Connection) threadLocal.get(); try { if (conn == null) { conn = ConnectionProvider.getConnection(); conn.setAutoCommit(false); threadLocal.set(conn); } } catch (Exception e) { e.printStackTrace(); throw new Exception("数据源错误..."); } return conn; } public static void closeConnection() throws Exception { Connection conn = (Connection) threadLocal.get(); if (conn != null && !conn.isClosed()) {