据库连接: public class DBConn { private static DBConn dc; private Connection conn = null; private Statement stmt = null; private DBConn() { }
public static DBConn instance() { if (dc == null) { dc = new DBConn(); } return dc; } public Statement openStmt() { if (stmt == null) { conn = getConn(); try { stmt = conn.createStatement(); } catch (Exception e) { System.err.println("创建 Statement 异常: " + e.getMessage()); } } return stmt; }
public void closeStmt() { if (stmt != null) { try { stmt.close(); } catch (Exception e) { System.err.println("Statement 关闭异常"); } } if (conn != null) { try { conn.close(); } catch (Exception e) { System.err.println("数据库关闭异常"); } }
} private Connection getConn() { if (conn == null) { try { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/j2ee"); ds.setUsername("root"); ds.setPass
word("123456"); conn = ds.getConnec
tion(); } catch (Exception e) { e.printStackTrace(); } } return conn; } } 》C3P0 连接池
Hibernate 推荐使用该优秀的连接池,它实现了 JDBC3.0 规范的部分功能,故其性能更加突出,该池不仅可自 动清理不再使用的 Connection,还可以自动清理 Statement 和 ResultSet.C3P0 连接池需要 jre1.3 以上,推 荐 jre1.4 若需使用 C3P0 连接池,应将包 c3p0-0.8.5.jar 文件复制进系统.下面代码是通过 C3P0 连接池获得数据库连 接: public class DBConn { private static DBConn dc; private Connection conn = null; private Statement stmt = null; private DBConn() { } public static DBConn instance() { if (dc == null) { dc = new DBConn(); } return dc; } public Statement openStmt() { if (stmt == null) {
conn = getConn(); try { stmt = conn.createStatement(); } catch (Exception e) { System.err.println("创建 Statement 异常: " + e.getMessage()); } } return stmt; } public void closeStmt() { if (stmt != null) { try { stmt.close(); } catch (Exception e) { System.err.println("Statement 关闭异常"); }
} if (conn != null) { try { conn.close(); } catch (Exception e) { System.err.println("数据库关闭异常"); } } } public Connection getConn() { if (conn == null) { try { ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass("com.
mysql.jdbc.Driver"); ds.setJdbcUrl("jdbc:mysql://localhost:3306/
j2ee"); ds.setUser("root"); ds.setPassword("32147");
ds.setMaxPoolSize(40); ds.setMinPoolSize(2); ds.setMaxStatements(180); conn = ds.getConnection(); } catch (Exception e) { e.printStackTrace(); } } return conn; } } #3、Spring 的 JDBC 体系 #3、 core、datasource、 个包组成. 》Spring 提供的 JDBC 抽象框架由 core、datasource、object 和 support4 个包组成. core 包含 Spring JDBC 抽象的核心类,包含各种 SQLExceptionTranslator,用于将 SQLException 转化 成 spring 的异常继承体系,还有 DataFileMaxValueIncrementer 实现,以