2种方式
1.导入c3p0的jar
- //c3p0数据库连接池使用方法
- public static void main(String[] args) throws Exception {
- //创建数据库源对象
- ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
- //通过配置文件mysql.properties 来获取数据库信息
- //创建properties对象
- Properties properties = new Properties();
- //读取mysql.properties文件 这边有异常我们直接抛出
- properties.load(new FileInputStream("src//mysql.properties"));
- //得到对应的key
- //用户名
- String user = properties.getProperty("user");
- //密码
- String password = properties.getProperty("password");
- //数据库连接地址
- String url = properties.getProperty("url");
- //数据库连接驱动
- String driver = properties.getProperty("driver");
-
- //给数据源comboPooledDataSource添加相关的参数
- //驱动
- comboPooledDataSource.setDriverClass(driver);
- //地址
- comboPooledDataSource.setJdbcUrl(url);
- //用户名
- comboPooledDataSource.setUser(user);
- //密码
- comboPooledDataSource.setPassword(password);
- //初始连接个数
- comboPooledDataSource.setInitialPoolSize(10);
- //最大连接个数
- comboPooledDataSource.setMaxPoolSize(50);
- //最小连接个数
- comboPooledDataSource.setMinPoolSize(5);
- //这个方法就是从DataSource接口实现的
- Connection connection = comboPooledDataSource.getConnection();
- //设置 增加的sql语句
- String sql = "insert into user value(?,?)";
- //得到preparedStatement对象
- PreparedStatement preparedStatement = connection.prepareStatement(sql);
- //给参数赋值 1就是第一个? admin就是给参数值
- preparedStatement.setString(1, "admin");
- preparedStatement.setString(2, "admin");
- //执行对数据库的操作
- int i = preparedStatement.executeUpdate();
- if (i > 0) {
- System.out.println("增加成功");
- }
- //关闭数据库连接池资源
- connection.close();
- preparedStatement.close();
-
- }
- user=用户名
- password=密码
- url=jdbc:mysql://localhost:3306/数据库名
- driver=com.mysql.jdbc.Driver
第二种方式配置文件连接
- //第二种方式
- public void c3p0Test02() throws Exception {
-
- //创建数据库源对象 zx 就是xml文件的
- ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("name");
- //这个方法就是从DataSource接口实现的
- Connection connection = comboPooledDataSource.getConnection();
- //设置 增加的sql语句
- String sql = "insert into user value(?,?)";
- //得到preparedStatement对象
- PreparedStatement preparedStatement = connection.prepareStatement(sql);
- //给参数赋值 1就是第一个? admin就是给参数值
- preparedStatement.setString(1, "admin");
- preparedStatement.setString(2, "admin");
- //执行对数据库的操作
- int i = preparedStatement.executeUpdate();
- if (i > 0) {
- System.out.println("增加成功");
- }
- //关闭数据库连接池资源
- connection.close();
- preparedStatement.close();
-
- }
配置文件信息
-
-
"name"> -
"driverClass">com.mysql.jdbc.Driver -
-
"jdbcUrl">jdbc:mysql://127.0.0.1:3306/数据库名称 -
-
"user">用户名 -
-
"password">密码 -
-
"acquireIncrement">5 -
-
"initialPoolSize">10 -
-
"minPoolSize">5 -
-
"maxPoolSize">10 -
-
-
"maxStatements">5 -
-
-
"maxStatementsPerConnection">2 -
只是简单的使用 有不足的地方请大佬指点指点