C3p0
C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring等。
连接池的使用
1. 导包
2.
2.导入配置文件(不是必须,但是在企业里面一定使用配置文件)
如果不使用配置文件,就在代码中设置数据库参数4个
项目分为 开发环境和运行环境 ,在开发时,开发人员接触不到公司实际数据库。
数据是机密,但是开发后也要更改数据库,但是不需要更改代码,那就是需要使用配置文件
3. 导入自己写的工具类(初始化连接池,获得连接的方法)
4. 在DAO中使用工具类获得连接 或者连接池(有的工具类可以自动帮我们去创建连接)
比如dbutils 工具类
QueryRunner qr = new QueryRunner(C3p0Util.getDataSource());
配置文件
Java中的以写键值对的配置文件专门提供了这样的类和文件名
user=root password=root driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/orderdinner
Properties 文件后缀名
Properties 读取 .properties 文件的类
读取配置配置文件
1. 将配置文件变成流
2. 用java提供的 Properties 类去加载这个流
3. 调用 properties 对象的get Property 的方法,这个方法需要一个参数 ,键名返回的是一个值(字符串型)。
public static void main(String[] args) { //获得一个资源 以流的方式 InputStream in = Demo.class.getClassLoader().getResourceAsStream("database.properties"); Properties properties = new Properties(); //java中读取properties文件的类 创建对象 try { properties.load(in); //通过load 读取inputstream流 String user = properties.getProperty("user"); //通过键值名获得对应的值 String password = properties.getProperty("password"); //同上 String driverClass = properties.getProperty("driverClass"); //同上 String jdbcUrl = properties.getProperty("jdbcUrl"); //同上 System.out.println(user); System.out.println(password); System.out.println(driverClass); System.out.println(jdbcUrl); } catch (IOException e) { e.printStackTrace(); } }
c3p0配置文件
<c3p0-config> <named-config name="mysql"> <property name="user">root</property>
<property name="password">root</property>
<property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/orderdinner</property> </named-config> </c3p0-config>
public class C3p0Util { private static ComboPooledDataSource dataSource = null; static { dataSource = new ComboPooledDataSource("mysql"); } public static ComboPooledDataSource getDataSource(){ return dataSource; } public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } }