javaweb_day05_data connection pool JDBC

Today's content

The content of the last lesson consumes a lot of memory and is more troublesome. At this time, I made a container, and I applied for a lot of connection objects to this container. After creating it, the user will not open up space to the bottom of the system. He will take a connection object from the container, and after using it, it will return the connection object to the container. In this case, the speed of access becomes faster. At this time, we call this container the database connection pool, which stores the database connection. . 
1. database connection pool 
2. Spring JDBC: JDBC Template

 

Database connection pool

1. 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 accesses the database, the connection object is obtained from the container. After the user accesses the database, the connection object is returned to the container. 
2. Benefits: 
    1. conserve resources 
    2. The user access efficiency 
3. achieved: 
    in DataSource javax.sql packages: 1. Standard Interface 
        1. Method: 
            * Get the connection: the getConnection (), this method of obtaining connection 
            * 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 the return connection 
    2. Generally, we do not realize it, there are database vendors to achieve 
        1. C3P0: database connection pool technology 
        2. Druid: database connection pool implementation technology, provided by Alibaba
4. C3P0: Database Connection Pool Technology 
    * Steps: 
        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. Definition Configuration file: 
            * Name: c3p0.properties or c3p0-config.xml 
            * Path: directly put the file in the src directory. 
        3. Create a core object database connection pool object ComboPooledDataSource 
        4. Get connected: the getConnection 
    * Code: 
         // Create a database connection pool object. 
        The DataSource ComboPooledDataSource new new DS = (); 
        // get a connection objects 2. 
        Connection Conn = ds.getConnection (); 
5. Druid: Database connection pool implementation technology, provided by Alibaba. 
    1. Steps: 
        1. Import the jar package druid-1.0.9.jar 
        2. Define the configuration file: 
            * It 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 factory 
        5. Get connection: getConnection 
    * code: 
         //3. Load configuration file 
        Properties pro = new Properties(); 
        InputStream is = DruidDemo.class.getClassLoader(). getResourceAsStream("druid.properties"); 
        pro.load(is); 
        //4. Get the connection pool object 
        DataSource ds = DruidDataSourceFactory.createDataSource(pro); 
        //5. Get the connection 
        Connection conn = ds.getConnection(); 
    2 . Define tool class 
        1. Define a class JDBCUtils 
        2. Provide static code block to load configuration file and initialize connection pool object 
        3. Provide method 
            1. Get connection method: Get connection through database connection pool
            2. Release resources 
            3. Get connection pool method
    * Code: 
        public class JDBCUtils { 
            // member variable. 1 define the DataSource. 
            Private the DataSource static DS; 
            static { 
                the try { 
                    // load configuration file. 1. 
                    The Properties Pro new new = the Properties (); 
                    pro.load (JDBCUtils.class.getClassLoader ( ).getResourceAsStream("druid.properties")); 
                    //2. Get DataSource 
                    ds = DruidDataSourceFactory.createDataSource(pro); 
                } catch (IOException e) { 
                    e.printStackTrace(); 
                } 
            } 
            /** 
             * Get connection
         
                } catch (Exception e) { 
                    e.printStackTrace ();
        
             */
            public static Connection getConnection() throws SQLException {
                return ds.getConnection();
            }
        
            /**
             * 释放资源
             */
            public static void close(Statement stmt,Connection conn){
               /* if(stmt != null){
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
        
                if(conn != null){
                    try { 
                        conn.close();//Return the connection 
                    } catch (SQLException e) {
                        e.printStackTrace(); 
                    } 
                }*/ 
        
               close(null,stmt,conn); 
            }

 

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

 

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

 

                if(stmt != null){ 
                    try { 
                        stmt.close(); 
                    } catch (SQLException e) { 
                        e.printStackTrace(); 
                    } 
                } 
        
                if(conn != null){ 
                    try { 
                        conn.close();//Return Connection 
                    } catch (SQLException e) { 
                        e.printStackTrace(); 
                    } 
                } 
            } 
        
            /** 
             * Get the connection pool method 
             */ 
         
            public static DataSource getDataSource(){
                return ds; 
            } 
        
        }

Spring JDBC

* Spring framework's simple encapsulation of JDBC. A JDBCTemplate object is provided to simplify the development of JDBC 
* Steps: 
    1. Import the jar package 
    2. Create a JdbcTemplate object. Dependent on the data source the DataSource 
        * = Template JdbcTemplate new new JdbcTemplate (DS); 
    3. a method call to complete JdbcTemplate CRUD operations 
        * update (): DML statement is executed. Add, delete, and modify statements 
        * queryForMap(): query results encapsulate the result set as a map collection, use the column name as the key, and the value as the value, encapsulate this record as a map collection 
            * Note: The length of the result set of the query by this method It can only be 1 
        * queryForList(): Query results encapsulate 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 the result, save the result Encapsulated 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 results, the results are wrapped object 
            * generally used for the polymerization query function 
    4. Exercise: 
        * Requirements: 
            1. Review No. 1 salary data from 10,000 
            to add a record 2. 
            delete record just added 
            4 the query id record 1, packaged as a set of Map 
            5. query all records, packaged as List 
            6. the query all records will be packaged as a set of List Emp object 
            7. the total number of query records 
        * Code: 
            import cn.itcast.domain.Emp; 
            import cn.itcast.utils.JDBCUtils; 
            import org.junit.Test; 
            import org.springframework.jdbc.core.BeanPropertyRowMapper; 
            import org.springframework.jdbc.core.JdbcTemplate;
            
            import org.springframework.jdbc.core.RowMapper; 
             
            import java.sql.Date;
            import java.sql.ResultSet; 
            import java.sql.SQLException; 
            import java.util.List; 
            import java.util.Map; 
            
            public class JdbcTemplateDemo2 { 
            
                //Junit unit test, yes Let the method execute independently

 

                //1. Get JDBCTemplate object 
                private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); 
                /** 
                 * 1. Modify the salary of No. 1 data to 10000 
                 */ 
                @Test 
                public void test1(){ 
            
                    //2. Definition sql 
                    String sql = "update emp set salary = 10000 where id = 1001"; 
                    //3. Execute sql 
                    int count = template.update(sql); 
                    System.out.println(count); 
                } 
            
                /** 
                 * 2. Add A record 
                 */ 
                @Test
                public void test2(){ 
                    String sql = "insert into emp(id,ename,dept_id) values(?,?,?)"; 
                    int count = template.update(sql, 1015, "郭靖", 10); 
                    System. out.println(count); 
            
                } 
            
                /** 
                 * 3. Delete the record just added 
                 */ 
                @Test 
                public void test3(){ 
                    String sql = "delete from emp where id = ?"; 
                    int count = template.update(sql , 1015); 
                    System.out.println(count); 
                } 
            
                /** 
                 * 4. Query the record with id 1001 and encapsulate it as a Map collection
                 * Note: The length of the result set of this method query can only be 1 
                    String sql = "select * from emp";
                 */ 
                @Test 
                public void test4(){ 
                    String sql = "select * from emp where id =? Or id = ?"; 
                    Map<String, Object> map = template.queryForMap(sql, 1001,1002); 
                    System.out .println(map); 
                    //{id=1001, ename=Sun Wukong, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20} 
            
                } 
            
                /** 
                 * 5. Query all records and encapsulate them as List 
                 */ 
                @Test 
                public void test5(){ 
                    List<Map<String, Object>> list = template.queryForList(sql);
            
                    for (Map<String, Object> stringObjectMap: list) { 
                        System.out.println(stringObjectMap); 
                    } 
                } 
            
                /** 
                 * 6. Query all records and encapsulate them as a List collection of Emp objects 
                 */ 
            
                @Test 
                public void test6 (){ 
                    String sql = "select * from emp"; 
                    List<Emp> list = template.query(sql, new RowMapper<Emp>() { 
            
                        @Override 
                        public Emp mapRow(ResultSet rs, int i) throws SQLException {
                            Emp emp = new Emp(); 
                            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.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: list) { 
                        System.out.println(emp); 
                    } 
                } 
            
                /** 
                 * 6. Query all records and encapsulate them as a List collection of Emp objects 
                 */ 
            
                @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. Query the total number of records 
                 */
            
                @Test
                public void test7(){
                    String sql = "select count(id) from emp";
                    Long total = template.queryForObject(sql, Long.class);
                    System.out.println(total);
                }
            
            }

Guess you like

Origin blog.csdn.net/qq_34159161/article/details/106984326