天天看點

資料庫連接配接池、JDBCTemplate對象(快速入門)

資料庫連接配接池

1. 概念:其實就是一個容器(集合),存放資料庫連接配接的容器。
	    當系統初始化好後,容器被建立,容器中會申請一些連接配接對象,當使用者來通路資料庫時,從容器中擷取連接配接對象,使用者通路完之後,會将連接配接對象歸還給容器。

2. 好處:
	1. 節約資源
	2. 使用者通路高效

3. 實作:
	1. 标準接口:DataSource   javax.sql包下的
		1. 方法:
			* 擷取連接配接:getConnection()
			* 歸還連接配接:Connection.close()。如果連接配接對象Connection是從連接配接池中擷取的,那麼調用Connection.close()方法,則不會再關閉連接配接了。而是歸還連接配接

	2. 一般我們不去實作它,有資料庫廠商來實作
		1. C3P0:資料庫連接配接池技術
		2. Druid:資料庫連接配接池實作技術,由阿裡巴巴提供的


4. C3P0:資料庫連接配接池技術
	* 步驟:
		1. 導入jar包 (兩個) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
			* 不要忘記導入資料庫驅動jar包
		2. 定義配置檔案:
			* 名稱: c3p0.properties 或者 c3p0-config.xml
			* 路徑:直接将檔案放在src目錄下即可。

		3. 建立核心對象 資料庫連接配接池對象 ComboPooledDataSource
		4. 擷取連接配接: getConnection
	* 代碼:
		 //1.建立資料庫連接配接池對象
        DataSource ds  = new ComboPooledDataSource();
        //2. 擷取連接配接對象
        Connection conn = ds.getConnection();
5. Druid:資料庫連接配接池實作技術,由阿裡巴巴提供的
	1. 步驟:
		1. 導入jar包 druid-1.0.9.jar
		2. 定義配置檔案:
			* 是properties形式的
			* 可以叫任意名稱,可以放在任意目錄下
		3. 加載配置檔案。Properties
		4. 擷取資料庫連接配接池對象:通過工廠來來擷取  DruidDataSourceFactory
		5. 擷取連接配接:getConnection
	* 代碼:
		 //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();
	2. 定義工具類
		1. 定義一個類 JDBCUtils
		2. 提供靜态代碼塊加載配置檔案,初始化連接配接池對象
		3. 提供方法
			1. 擷取連接配接方法:通過資料庫連接配接池擷取連接配接
			2. 釋放資源
			3. 擷取連接配接池的方法
           

代碼:

public class JDBCUtils {

    //1.定義成員變量 DataSource
    private static DataSource ds ;

    static{
        try {
            //1.加載配置檔案
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.擷取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } 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();//歸還連接配接
            } 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();//歸還連接配接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 擷取連接配接池方法
     */

    public static DataSource getDataSource(){
        return  ds;
    }

}
           

Spring JDBC

* Spring架構對JDBC的簡單封裝。提供了一個JDBCTemplate對象簡化JDBC的開發
* 步驟:
	1. 導入jar包
	2. 建立JdbcTemplate對象。依賴于資料源DataSource
		* JdbcTemplate template = new JdbcTemplate(ds);

	3. 調用JdbcTemplate的方法來完成CRUD的操作
		* update():執行DML語句。增、删、改語句
		* queryForMap():查詢結果将結果集封裝為map集合,将列名作為key,将值作為value 将這條記錄封裝為一個map集合
			* 注意:這個方法查詢的結果集長度隻能是1
		* queryForList():查詢結果将結果集封裝為list集合
			* 注意:将每一條記錄封裝為一個Map集合,再将Map集合裝載到List集合中
		* query():查詢結果,将結果封裝為JavaBean對象
			* query的參數:RowMapper
				* 一般我們使用BeanPropertyRowMapper實作類。可以完成資料到JavaBean的自動封裝
				* new BeanPropertyRowMapper<類型>(類型.class)
		* queryForObject:查詢結果,将結果封裝為對象
			* 一般用于聚合函數的查詢

	4. 練習:
		* 需求:
			1. 修改1号資料的 salary 為 10000
			2. 添加一條記錄
			3. 删除剛才添加的記錄
			4. 查詢id為1的記錄,将其封裝為Map集合
			5. 查詢所有記錄,将其封裝為List
			6. 查詢所有記錄,将其封裝為Emp對象的List集合
			7. 查詢總記錄數
           

代碼:

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單元測試,可以讓方法獨立執行


    //1. 擷取JDBCTemplate對象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * 1. 修改1号資料的 salary 為 10000
     */
    @Test
    public void test1(){

        //2. 定義sql
        String sql = "update emp set salary = 10000 where id = 1001";
        //3. 執行sql
        int count = template.update(sql);
        System.out.println(count);
    }

    /**
     * 2. 添加一條記錄
     */
    @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.删除剛才添加的記錄
     */
    @Test
    public void test3(){
        String sql = "delete from emp where id = ?";
        int count = template.update(sql, 1015);
        System.out.println(count);
    }

    /**
     * 4.查詢id為1001的記錄,将其封裝為Map集合
     * 注意:這個方法查詢的結果集長度隻能是1
     */
    @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=孫悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}

    }

    /**
     * 5. 查詢所有記錄,将其封裝為List
     */
    @Test
    public void test5(){
        String sql = "select * from emp";
        List<Map<String, Object>> list = template.queryForList(sql);

        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }
    }

    /**
     * 6. 查詢所有記錄,将其封裝為Emp對象的List集合
     */

    @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. 查詢所有記錄,将其封裝為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(id) from emp";
        Long total = template.queryForObject(sql, Long.class);
        System.out.println(total);
    }

}