JDBC basic knowledge 2 [Druid connection pool, Spring JDBC]

Today's content

  1. Database connection pool

  2. Spring JDBC : JDBC Template

Database connection pool

concept

In fact, it is a container (collection), a container for storing database connections.
After the system is initialized, the container is created, and some connection objects are applied for in the container. When a user comes to access the database, the connection object is obtained from the container. After the user accesses the database, the connection object is returned to the container.

benefit

  1. save resources
  2. User access is efficient

achieve

Standard interface: DataSource javax.sql package

method:

  • Get connection: getConnection()
  • Return the connection: Connection.close(). If the connection object Connection is obtained from the connection pool, then the Connection.close() method is called, and the connection will no longer be closed. But return the connection

Generally we do not implement it, database vendors do it

  1. C3P0: Database connection pool technology
  2. Druid: Database connection pool implementation technology, provided by Alibaba

C3P0: Database connection pool technology

step:

  1. Import the jar package (two) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar,

    • Don't forget to import the database driver jar package
  2. Define the configuration file:

    • Name: c3p0.properties or c3p0-config.xml
    • Path: Put the file directly in the src directory.
  3. Create a core object database connection pool object ComboPooledDataSource

  4. Get connection: getConnection

Code:

	//1.创建数据库连接池对象
	DataSource ds  = new ComboPooledDataSource();
  	//2. 获取连接对象
  	Connection conn = ds.getConnection();

Druid database connection pool technology

Database connection pool implementation technology, provided by Alibaba.

step:

  1. Import the jar package druid-1.0.9.jar
  2. Define the configuration file:
    • Is in the form of properties
    • Can be called any name, can be placed in any directory
  3. Load the configuration file. Properties
  4. Get database connection pool object: get DruidDataSourceFactory through the factory
  5. Get connection: getConnection

Code:

//3.加载配置文件
        Properties pro = new Properties();
        InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        //4.获取连接池对象
        DataSource ds = DruidDataSourceFactory.createDataSource(pro);
        //5.获取连接
        Connection conn = ds.getConnection();

Define tool class

  1. Define a class JDBCUtils
  2. Provide static code blocks to load configuration files and initialize connection pool objects
  3. Provide method
    1. Get connection method: get connection through database connection pool
    2. Release resources
    3. How to get the connection pool

Code:

Main method class:

public class Druid_Demo1 {
    
    

    public static void main(String[] args) throws Exception {
    
    
        //1.导入jar包

        //2.导入配置文件
        Properties pro = new Properties();
        InputStream is = 					Druid_Demo1.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        DataSource ds = DruidDataSourceFactory.createDataSource(pro);
        for (int i = 1; i <= 11; i++) {
    
    
            Connection conn = ds.getConnection();
            System.out.println("第"+i+"次"+conn);
            if(i == 5){
    
    
                conn.close();
            }
        }

    }
}

JDBCUtils tool class:

public class JDBCUtils {
    
    

    private static DataSource ds;

    static {
    
    
        try {
    
    
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
    
    
        return ds.getConnection();
    }

    public static void close(Statement stmt, Connection conn){
    
    
        close(null,stmt,conn);
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn){
    
    

        if(rs != null){
    
    
            try {
    
    
                rs.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }

        if(stmt != null){
    
    
            try {
    
    
                stmt.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }

        if(conn != null){
    
    
            try {
    
    
                conn.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }

    public static DataSource getDataSource(){
    
    
        return ds;
    }
}

Results of the:

Insert picture description here

Use case code:

public class Druid_Demo2 {
    
    

    public static void main(String[] args) {
    
    
        Druid_Demo2 dd = new Druid_Demo2();
        dd.findAll();
    }

    public void findAll(){
    
    
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
    
    
            conn = JDBCUtils.getConnection();
            String sql = "insert into dept values (80,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,"开发部");
            pstmt.setString(2,"海海海");
            int count = pstmt.executeUpdate();
            if(count > 0){
    
    
                System.out.println("插入成功!");
            }else System.out.println("插入失败!");

        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            JDBCUtils.close(pstmt,conn);
        }
    }
}

Results of the:

Insert picture description here

Spring JDBC

Spring framework's simple encapsulation of JDBC. Provides a JDBCTemplate object to simplify JDBC development

step

1. Import the jar package

2. Create a JdbcTemplate object. Depends on the data source DataSource

JdbcTemplate template = new JdbcTemplate(ds);

3. Call the JdbcTemplate method to complete the CRUD operation

update(): Execute DML statement. Add, delete, and modify sentences

queryForMap(): The query result encapsulates the result set as a map collection, the column name is used as the key, the value is used as the value, and the record is encapsulated as a map collection

  • Note: The length of the result set of this method query can only be 1

queryForList(): The query result encapsulates the result set as a list collection

  • Note: Encapsulate each record as a Map collection, and then load the Map collection into the List collection

query(): query result, encapsulate the result as a JavaBean object

  • Query parameter: RowMapper

    • Generally we use the BeanPropertyRowMapper implementation class. Can complete the automatic encapsulation of data to JavaBean
    • new BeanPropertyRowMapper<type>(type.class)
  • queryForObject: query result, encapsulate the result as an object

    • Generally used for query of aggregate functions

Basic case

public class JDBCTemplate_Demo1 {
    
    

    public static void main(String[] args) {
    
    

        JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
        String sql = "delete from dept where id = ?";
        int count = template.update(sql, 80);
        if(count > 0) System.out.println("删除成功!");
        else System.out.println("删除失败!");
    }
}

Results of the:
Insert picture description here

Exercise

demand:

  1. Modify the salary of No. 1 data to 10000
  2. Add a record
  3. Delete the record just added
  4. Query the record with id 1 and encapsulate it as a Map collection
  5. Query all records and encapsulate them as List
  6. Query all records and encapsulate them as a List collection of Emp objects
  7. Query the total number of records
public class JDBCTemplate_Demo2 {
    
    

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /*1. 修改1号数据的 salary 为 10000*/
    @Test
    public void test1(){
    
    

        String sql = "update emp set salary = 15000 where id = 1001";
        int count = template.update(sql);
        System.out.println(count);
        if(count > 0) System.out.println("修改成功!");
        else System.out.println("修改失败!");
    }

    /*2. 添加一条记录*/
    @Test
    public void test2(){
    
    
        String sql = "insert into emp(id,ename,salary,dept_id) values(?,?,?,?)";
        int count = template.update(sql, 1015, "郭靖", 25000, 50);
        System.out.println(count);
        if(count > 0) System.out.println("插入数据成功!");
        else System.out.println("插入数据失败!");
    }

    /*3.删除刚才添加的记录*/
    @Test
    public void test3(){
    
    
        String sql = "delete from emp where id = ?";
        int count = template.update(sql, 1015);
        System.out.println(count);
        if(count > 0) System.out.println("删除成功!");
        else System.out.println("删除失败!");
    }

    /*4.查询id为1的记录,将其封装为Map集合*/
    @Test
    public void test4(){
    
    
        String sql = "select * from emp where id = ?";
        Map<String, Object> map = template.queryForMap(sql, 1001);
        System.out.println(map);

    }

    /*5. 查询所有记录,将其封装为List*/
    @Test
    public void test5(){
    
    
        String sql = "select * from emp";
        List<Map<String, Object>> list = template.queryForList(sql);
        for (Map<String, Object> maps : list) {
    
    
            System.out.println(maps);
        }
    }

    /*6. 查询所有记录,将其封装为Emp对象的List集合*/
    @Test
    public void test6(){
    
    
        String sql = "select * from emp";
        List<Emp> lsit = template.query(sql, new RowMapper<Emp>() {
    
    

            @Override
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
    
    
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");

                Emp emp = new Emp();
                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);
                return emp;
            }
        });
        for (Emp emp : lsit) {
    
    
            System.out.println(emp);
        }

    }

    /*6. 查询所有记录,将其封装为Emp对象的List集合*/
    @Test
    public void test6_2(){
    
    
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : list) {
    
    
            System.out.println(emp);
        }
    }

    /*7. 查询总记录数*/
    @Test
    public void test7(){
    
    
        String sql = "select count(*) from emp";
        Long count = template.queryForObject(sql, Long.class);
        System.out.println("记录总数为:"+count);
    }
}
  

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/109117949