时间:2021-07-01 10:21:17 帮助过:29人阅读
使用步骤:
1.导入相应的jar包即可
2.然后再类中使用
案例1:
package com.itheima.c3p0; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Demo1 { public static void main(String[] args) { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try{ //方式1: ComboPooledDataSource dataSource=new ComboPooledDataSource(); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/day11"); dataSource.setUser("root"); dataSource.setPassword("169500"); con=dataSource.getConnection(); ps = con.prepareStatement("select * from account"); rs = ps.executeQuery(); while (rs.next()) { String name = rs.getString("name"); System.out.println(name); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { rs = null; } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { ps = null; } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } finally { con = null; } } } } }方式二:在src目录下建立一个配置文件名为c3p0-config.xml文件,使用c3p0数据库连接池的类会自动找到在类字节码文件的这个配置文件:
配置如下:
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/day11</property> <property name="user">root</property> <property name="password">169500</property> </default-config> </c3p0-config>在类中使用:
package com.itheima.c3p0; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Demo2 { public static void main(String[] args) { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try{ //方式1: ComboPooledDataSource dataSource=new ComboPooledDataSource();//会默认寻找配置文件 con=dataSource.getConnection(); ps = con.prepareStatement("select * from account"); rs = ps.executeQuery(); while (rs.next()) { String name = rs.getString("name"); System.out.println(name); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { rs = null; } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { ps = null; } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } finally { con = null; } } } } }运行结果:
版权声明:本文为博主原创文章,未经博主允许不得转载。
黑马day11 c3p0数据库连接池
标签:c3p0数据库连接池