当前位置:网站首页>Database connection pool & jdbctemplate

Database connection pool & jdbctemplate

2022-07-05 12:33:00 It Chunhe

Catalog

1、 Database connection pool

1.1、 brief introduction

1.2、 Use (quickstart)

1.2.1、C3P0 Database connection pool

1.2.2、Druid Database connection pool  

2、JDBCTemplate Use


1、 Database connection pool

1.1、 brief introduction

1、 Database connection pool : In short , It's actually a container ( aggregate ), Container for storing database connection objects .

  When the system is initialized , The container is created , Some connection objects will be requested in the container , When the user comes to access the database , Get the connection object from the container , After the user visits , The connection object is returned to the container .

2. The benefits of using connection pools :
    1. Saving resource , Lifting performance
    2. Efficient user access , Faster response

3. Realization :
    1. Standard interface :DataSource    be located javax.sql It's a bag
        1. Method :
              Get the connection :getConnection()
             Return connection :Connection.close().

If the connection object Connection It's taken from the connection pool , So called Connection.close() Method , The connection will no longer be closed . But return the connection

4、 Common database connection pool :
        1. C3P0: Database connection pool technology
        2. Druid: Database connection pool implementation technology , Provided by Alibaba

5、 Use of jar Package download address :jar Package download

1.2、 Use (quickstart)

1.2.1、C3P0 Database connection pool

Use steps :    

       1. Import jar package ( Two ) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
             Don't forget to import database drivers jar package   jar Package download address
        2. Define configuration file :
            name : c3p0.properties perhaps c3p0-config.xml
            route : Put the document directly in src Under the directory .

        3. Create core objects Database connection pool object ComboPooledDataSource
        4. Get the connection : getConnection

1、 Import jar package

2、 To write c3p0.xml The configuration file

<c3p0-config>
  <!--  Use the default configuration to read connection pool objects  -->
  <default-config>
  	<!--   Connection parameters  -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/day10</property>
    <property name="user">root</property>
    <property name="password">123456</property>
    
    <!--  Connection pool parameters  -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">10</property>
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
    <!--   Connection parameters  -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/study</property>
    <property name="user">root</property>
    <property name="password">123456</property>
    
    <!--  Connection pool parameters  -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>

3、 code

public class C3p0Test {
    public static void main(String[] args) throws SQLException {
        // TODO 1、 obtain datasource
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        // TODO 2、 obtain connection
        Connection connection = dataSource.getConnection();
        // TODO 3、 Definition sql
        String sql = "select * from person";
        // TODO 4、 perform sql
        ResultSet resultSet = connection.createStatement().executeQuery(sql);
        // TODO 5、 Print query data 
        while (resultSet.next()){
            String name = resultSet.getString("name");
            String email = resultSet.getString("email");
            System.out.println(name + "=======" + email);
        }
        // TODO 6、 Release resources 
        resultSet.close();
        connection.close();


    }

}


1.2.2、Druid Database connection pool  

Druid: Database connection pool implementation technology , Provided by Alibaba
    1. step :
        1. Import jar package druid-1.0.9.jar 
        2. Define configuration file :
             yes properties Formal
             You can call it anything , It can be placed in any directory
        3. Load profile Properties
        4. Get database connection pool object : From the factory  DruidDataSourceFactory
        5. Get the connection :getConnection

1、 Import jar package

2、 To write druid Configuration file for

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/day10
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

3、 code

public class DruidTest {
    public static void main(String[] args) throws Exception {
        // TODO 1、 Load profile 
        Properties properties = new Properties();
        InputStream is = DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
        properties.load(is);

        // TODO 2、 establish datasource
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

        // TODO 3、 Get database connection object 
        Connection connection = dataSource.getConnection();

        // TODO 4、 Print objects directly   See if you can get the database connection object 
        System.out.println(connection);

    }
}


2、JDBCTemplate Use

  Use JDBCTemplate It can greatly reduce our writing jdbc Code for To simplify our development

jdbctemplate A quick start to

1、 Import jar package   

2、 code

public class JDBCTemplate_quickstart {
    public static void main(String[] args) throws Exception {
        // TODO 1、 Load profile 
        Properties properties = new Properties();
        InputStream is = DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
        properties.load(is);

        // TODO 2、 establish datasource
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

        // TODO 3、 establish JDBCTemplate object   Need to pass on a datasource
        JdbcTemplate template = new JdbcTemplate(dataSource);

        // TODO 4、 Definition sql
        String sql = "update person set addr = ' panama ' where id = ?";
        int count = template.update(sql,5); //  take id by 5 Change your address to Panama 
        System.out.println(count); //  Number of rows affected  1

        // TODO  Use jdbcTemplate It can greatly simplify the amount of our code   Only care about sql
    }
}

3、 test

  But the above code is still a lot , Then the tool classes we extracted before are used

1、 Create a new one util package , Put the extracted tool classes into the toolkit

//  This is a jdbc Tool class of 
public class JdbcUtil {
    //  Define a member variable datasource
    private static DataSource dataSource;

    static {
        try {
            // 1、 establish properties Collection classes 
            Properties properties = new Properties();
            // 2、 Load profile 
            InputStream resourceAsStream = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(resourceAsStream);
           // 3、 Use database connection pool  druid
            dataSource = DruidDataSourceFactory.createDataSource(properties);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  return datasource Methods 
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }
    
    /**
     *  Get database connection object 
     * @return  Data connection objects 
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    /**
     *  Release resources 
     *
     * @param stmt
     * @param conn
     */
    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();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(PreparedStatement pstmt, Connection conn) {
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

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


    /**
     *  Release resources 
     *
     * @param stmt
     * @param 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();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(ResultSet rs, PreparedStatement 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();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

2、 Use JDBCTemplate

public class JDBCTemplate_quickstart2 {
    public static void main(String[] args) throws Exception {

        // 1、 Create a template object 
        JdbcTemplate template = new JdbcTemplate(JdbcUtil.getDataSource());
        // 2、 Definition sql
        String sql = "select count(*) from person";
        // 3、 Use template perform sql
        Integer count = template.queryForObject(sql, Integer.class);
        System.out.println(count);

    }
}

This makes it look more concise And we just need to focus on sql Sentence can be used

原网站

版权声明
本文为[It Chunhe]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140528425138.html