69期-Java SE-040_JDBC-4

C3P0 的使用

1、c3p0-config.xml 名称不能自定义

```xml
<c3p0-config>
    <named-config name="testc3p0">
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8</property>
        <property name="initialPoolSize">20</property>
        <property name="acquireIncrement">5</property>
        <property name="maxPoolSize">40</property>
        <property name="minPoolSize">2</property>
    </named-config>
</c3p0-config>
```

2、Java

```java
package com.southwind;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class Test2 {
    public static void main(String[] args) {
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource("testc3p0");
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
```

### DBUtils

DBUtils 是一个可以帮助开发者自动完成数据封装的工具,查询的结果直接返回一个对象或者一个集合。

ResultSetHandler 接口的实现类

- BeanHandler            将结果集映射成一个 POJO,适用于查询结果是一条记录的
- BeanListHandler      将结果集映射成一个 List,适用于查询结果是多条记录的
- MapHandler              将结果集映射成一个 Map,用 Map 的结构来描述数据
- MapListHandler        将结果集映射成一个 MapList,返回一个装载了 Map 对象的 List 集合

```java
package com.southwind.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.southwind.entity.People;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class Test3 {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource("testc3p0");
            connection = dataSource.getConnection();
            String sql = "select * from people";
            QueryRunner queryRunner = new QueryRunner();
//            List<People> list = queryRunner.query(connection,sql,new BeanListHandler<>(People.class),1);
//            System.out.println(list);
//            People people = queryRunner.query(connection,sql, new BeanHandler<>(People.class),1);
//            System.out.println(people);
//            String sql = "select * from people";
//            People people = queryRunner.query(connection,sql,new BeanHandler<>(People.class));
//            System.out.println(people);
//            List<People> list = queryRunner.query(connection,sql,new BeanListHandler<>(People.class));
//            System.out.println(list);
//            String sql = "select * from people where id = ?";
//            Map<String,Object> map = queryRunner.query(connection,sql,new MapHandler());
//            System.out.println(map.get("id"));
//            System.out.println(map.get("name"));
//            System.out.println(map.get("money"));
            List<Map<String,Object>> list = queryRunner.query(connection,sql,new MapListHandler());
            for(Map<String,Object> map:list){
                System.out.println(map.get("id")+"-"+map.get("name")+"-"+map.get("money"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
```

QueryRunner 除了可以简化查询操作,同时还可以简化增删改操作。

```java
package com.southwind.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;

public class Test4 {
    public static void main(String[] args) {
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource("testc3p0");
            Connection connection = dataSource.getConnection();
//            String sql = "insert into people(name,money) values(?,?)";
//            QueryRunner queryRunner = new QueryRunner();
//            int row = queryRunner.update(connection,sql,"小明",600);
//            System.out.println(row);

//            String sql = "update people set name = ?,money = ? where id = ?";
//            QueryRunner queryRunner = new QueryRunner();
//            int row = queryRunner.update(connection,sql,"小红",800,4);
//            System.out.println(row);

            String sql = "delete from people where id = ?";
            QueryRunner queryRunner = new QueryRunner();
            int row = queryRunner.update(connection,sql,4);
            System.out.println(row);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
```

c3p0-config.xml

<c3p0-config>
    <named-config name="testc3p0">
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8</property>
        <property name="initialPoolSize">20</property>
        <property name="acquireIncrement">5</property>
        <property name="maxPoolSize">40</property>
        <property name="minPoolSize">2</property>
    </named-config>
</c3p0-config>

People.java

package com.southwind.entity;

public class People {
    private Integer id;
    private String name;
    private Integer money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getMoney() {
        return money;
    }

    public void setMoney(Integer money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", money=" + money +
                ‘}‘;
    }

    public People(Integer id, String name, Integer money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

    public People() {
    }
}

Test.java

package com.southwind.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

public class Test {
    public static void main(String[] args) {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8");
            dataSource.setUser("root");
            dataSource.setPassword("root");
            dataSource.setInitialPoolSize(20);
            dataSource.setAcquireIncrement(5);
            dataSource.setMaxPoolSize(40);
            dataSource.setMinPoolSize(2);
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        } catch (SQLException e){
            e.printStackTrace();
        }
    }
}

Test2.java

package com.southwind.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.southwind.entity.People;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test2 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource("testc3p0");
            connection = dataSource.getConnection();
            String sql = "select * from people where id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,1);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                int money = resultSet.getInt(3);
                People people = new People(id,name,money);
                System.out.println(people);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(connection!=null){
                    connection.close();
                }
                if(preparedStatement!=null){
                    preparedStatement.close();
                }
                if(resultSet!=null){
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Test3.java

package com.southwind.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.southwind.entity.People;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class Test3 {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource("testc3p0");
            connection = dataSource.getConnection();
            String sql = "select * from people";
            QueryRunner queryRunner = new QueryRunner();
//            List<People> list = queryRunner.query(connection,sql,new BeanListHandler<>(People.class),1);
//            System.out.println(list);
//            People people = queryRunner.query(connection,sql, new BeanHandler<>(People.class),1);
//            System.out.println(people);
//            String sql = "select * from people";
//            People people = queryRunner.query(connection,sql,new BeanHandler<>(People.class));
//            System.out.println(people);
//            List<People> list = queryRunner.query(connection,sql,new BeanListHandler<>(People.class));
//            System.out.println(list);
//            String sql = "select * from people where id = ?";
//            Map<String,Object> map = queryRunner.query(connection,sql,new MapHandler());
//            System.out.println(map.get("id"));
//            System.out.println(map.get("name"));
//            System.out.println(map.get("money"));
            List<Map<String,Object>> list = queryRunner.query(connection,sql,new MapListHandler());
            for(Map<String,Object> map:list){
                System.out.println(map.get("id")+"-"+map.get("name")+"-"+map.get("money"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Test4.java

package com.southwind.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;

public class Test4 {
    public static void main(String[] args) {
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource("testc3p0");
            Connection connection = dataSource.getConnection();
//            String sql = "insert into people(name,money) values(?,?)";
//            QueryRunner queryRunner = new QueryRunner();
//            int row = queryRunner.update(connection,sql,"小明",600);
//            System.out.println(row);

//            String sql = "update people set name = ?,money = ? where id = ?";
//            QueryRunner queryRunner = new QueryRunner();
//            int row = queryRunner.update(connection,sql,"小红",800,4);
//            System.out.println(row);

            String sql = "delete from people where id = ?";
            QueryRunner queryRunner = new QueryRunner();
            int row = queryRunner.update(connection,sql,4);
            System.out.println(row);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

原文地址:https://www.cnblogs.com/HiJackykun/p/11182587.html

时间: 2024-11-09 00:58:25

69期-Java SE-040_JDBC-4的相关文章

69期-Java SE-035_MySQL-6 存储过程、SQL练习 -doing

### 存储过程 存储过程是一组为了完成特定功能的 SQL 语句集合,经过编译后存储在数据库中,用户通过指定存储过程的名称以及参数来执行相应的存储过程. 一次编写,多次调用,避免开发人员重复编写相同的 SQL 语句,存储过程是在数据库中存储和执行的,可以减少客户端和服务端之间的数据传输,从而提高效率. ### 优点 - 模块化的程序设计,只需要创建一次存储过程,以后就可以在程序中调用该存储过程任意次. - 执行速度更快,如果某个操作需要执行大量的 SQL 语句或者需要重复执行 SQL 语句,存储

69期-Java SE-031_MySQL-001-002 创建表、MySQL数据类型、数据的管理(数据库结构、数据表、数据)、SQL 函数

### 创建表 1.创建数据库 ```sql create database mstest default character set utf8 collate utf8_general_ci ``` 2.创建数据表 ```sql create table user( id int, name varchar(11) ) ``` Java 数据类型:基本数据类型 byte short int long double float boolean char ? 引用类型 MySQL 数据类型 - 整

69期-Java SE-002_变量、运算符-001-002

- 声明变量的数据类型和变量名. - 给内存空间赋值,该值就是变量值. - 通过变量名使用变量. ```java public class Hello { public static void main(String[] args) { //1.开辟内存空间,定义变量名 int num1; //2.赋值 num1 = 10; //3.使用变量 System.out.println(num1); } } ``` ```java public class Hello { public static

69期-Java SE-003_流程控制、循环-001-002

### 位运算符 十进制和二进制的转换. - 十进制转二进制:目标数除以二,如果能除尽,则该位计作零,如果除不尽,则该位计作一,再对商继续除以二,以此类推,直到商为零,然后将每一位的结果进行反序组合就是对应的二进制结果,10 转为二进制 1010,17 转为二进制 10001 - 二进制转十进制:从目标数最右侧算起,本位的数值乘以本位的权重,权重就是2的第几位的位数减一次方,如果第1位就是2的(1-1)次方,第2位就是2的(2-1)次方,第3位就是2的(3-1)次方…,将每一位的数值和本位权重相

69期-Java SE-004_循环、数组-001-002

Hello.java import java.util.Scanner; public class Hello { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = "yes"; int num; while(str.equals("yes")) { System.out.print("请输入学生编号:")

69期-Java SE-036_MySQL-7 SQL练习 -doing

第一道: 现有图书管理数据库的三个关系模式,他们的字段分别如下: 图书表:总编号, 分类号, 书名, 作者, 出版单位, 单价 读者表:借书证号, 单位, 姓名, 性别, 职称, 地址 借阅表:借书证号, 总编号, 借书日期 以上表对应的字段明细如下: book : b_no ,b_type ,b_name , b_author ,b_publish ,b_price reader : r_no , r_unit , r_name ,r_sex ,r_pro ,r_address borrow

69期-Java SE-005_二维数组、综合练习-001-002

Test.java public class Test { public static void main(String[] args) { int[] array = {73,80,62,93,96,87}; //求最大值 int max = array[0]; for(int i=1;i<array.length;i++) { if(array[i]>max) { max = array[i]; } } System.out.println("数组中的最大值是"+max

69期-Java SE-007_面向对象-1-001-002

Student.java public class Student { //定义属性 int id; String name; int age; int userFirstName; double myScore; //定义方法 public static int add(int num1,int num2) { return num1+num2; } public static void add2(int num1,int num2) { System.out.println(num1+num

69期-Java SE-009_面向对象-3-001-002

### 多态 一个事物有多种表现形态. - 定义方法时形参为父类,调用方法时传入的参数为子类对象. - 定义方法时返回值数据类型为父类,调用方法时返回子类对象. 具有继承关系的两个对象可以相互转换,子类转父类即父类引用指向子类对象,可以自动完成,无需强制转换,也叫做向上转型. 父类转子类即子类引用指向父类对象,不能自动完成转换,需要强制转换,也叫做向下转型. ### 抽象方法和抽象类型 如果一个方法只有方法声明而没有具体的方法实现,那么该方法就是抽象方法,在方法定义处使用 abstract 关键

69期-Java SE-008_面向对象-2-001-002

User.java public class User { public static String name; public static int num; static { num++; System.out.println("执行了静态代码块"); } static { System.out.println("static2"); } } Cashier.java package entity; public class Cashier { private M