数据库连接池,DBUtil的模板,Druid使用(重点)
一、DBUtil模板
public class DBUtilTest { public static Connection connection; public static final String URL = "jdbc:mysql:///demo"; public static final String USERNAME = ""; public static final String PASSWORD = ""; static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void testQuery() throws SQLException { connection = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "select * from emp where id = ?"; QueryRunner runner = new QueryRunner(); Emp query = runner.query(connection, sql, new BeanHandler<Emp>(Emp.class), 1); System.out.println(query); } public static void testQuery2() throws SQLException { connection = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "select * from emp"; QueryRunner runner = new QueryRunner(); List<Emp> query = runner.query(connection, sql, new BeanListHandler<Emp>(Emp.class)); query.forEach((x)->{ System.out.println(x); }); } public static void insert() throws SQLException { connection = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "insert emp values(null,?,?)"; QueryRunner runner = new QueryRunner(); runner.update(connection,sql,1,2); } public static void main(String[] args) throws SQLException { testQuery2(); } }
二、数据库连接池
数据库连接池是为了减少频繁开关连接的时间,分析应该具备几个属性
1.初始大小
2.每次扩容大小
3.连接池最大个数
4.空闲连接死亡时间
各种数据库连接池
- DBCP
- C3P0
- Druid
- hikariCP
2.1.DBCP模板
public static void main(String[] args) throws SQLException { // 数据库连接池资源 BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); basicDataSource.setUrl("jdbc:mysql:///demo"); basicDataSource.setUsername(""); basicDataSource.setPassword(""); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet rs = null; connection = basicDataSource.getConnection(); String sql = "select * from emp"; preparedStatement = connection.prepareStatement(sql); rs = preparedStatement.executeQuery(); while (rs.next()){ System.out.println(rs.getInt(1)+ rs.getString(2)+ rs.getString(3)); } connection.close(); }
2.2.C3P0
public static void main(String[] args) throws PropertyVetoException, SQLException { ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass( "com.mysql.cj.jdbc.Driver" ); //loads the jdbc driver cpds.setJdbcUrl( "jdbc:mysql://120.78.206.78:3306/demo" ); cpds.setUser("root"); cpds.setPassword("Root123.."); cpds.setMaxStatements( 180 ); Connection conn = cpds.getConnection(); System.out.println(conn); conn.close(); }
第二种参照官网,进行xml配置
2.3.druid
druid是性能最好的数据库连接池
dbcp和c3p0区别,c3p0会自动回收不使用的连接