JDBC連接池&JDBCTemplate

1 JDBC連接池

1.1 概念和實現

  • 概念

    就是 一個裝有Connection對象的容器,需要連接對象的時候就從容器中獲取,使用完畢之後自動歸還。

  • 實現

1、所有的連接池對象都必須實現DataSource接口。
2、所有連接池都有獲取連接的方法:getConnection();而且調用從連接池獲取連接的close()方法
不是關閉連接,而是歸還連接。

1.2 c3p0連接池

  • 使用步驟
1、導入開發jar包:c3p0-0.9.5.2.jar和mchange-commons-java-0.2.12.jar,不要忘了mysql驅動jar包。
2、創建src目錄下配置文件:c3p0.properties或者c3p0-config.xml
3、創建連接池對象
4、獲取連接
  • 注意事項
1、配置文件必須放在src目錄中(類路徑下)
2、配置文件的名稱必須是:c3p0.properties或者c3p0-config.xml

使用屬性文件代替xml文件

# 驅動全類名
c3p0.driverClass=com.mysql.jdbc.Driver
# 連接的url
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/db3
# 用戶名
c3p0.user=root
# 密碼
c3p0.password=root

# 初始化連接個數
c3p0.initialPoolSize=5
# 最大連接數
c3p0.maxPoolSize=15
# 超時時間
c3p0.checkoutTimeout=3000

1.3 druid連接池

  • 使用步驟
1、導入開發jar包:druid-1.0.9.jar,不要忘了mysql驅動jar包。
2、在src目錄下創建配置文件(將資料中的配置文件複製進去即可)druid.properties
3、加載properties屬性文件
4、獲取連接池對象:DruidDataSourceFactory.createDataSource(Properties pro);
5、獲取連接
  • 代碼示例
public static void main(String[] args) throws Exception {
  //加載配置文件
  Properties properties=new Properties();
  InputStream is = DruidDataSourceTest.class.getClassLoader().getResourceAsStream("druid.properties");
  properties.load(is);
  //3、獲取連接池對象:DruidDataSourceFactory.createDataSource(Properties pro);
  DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
  //4、獲取連接
  Connection conn = dataSource.getConnection();
  System.out.println("conn = " + conn);
}
  • 修改JDBCUtils工具類
/*
    目的:封裝連接池對象,一個應用程序有一個連接池就夠了
    做哪些事:
        1、加載properties配置文件
        2、初始化連接池對象
        3、對外提供一個方法獲取連接
        4、對外提供一個方法釋放資源
        5、對外提供一個獲取連接池對象的方法。
 */
public class JDBCUtils {
    private static DataSource ds;  //ctrl+alt+f
    static {
        //1、加載properties配置文件
        //1.1 創建Properties對象
        Properties properties=new Properties();
        //1.2 調用load方法
        InputStream is = JDBCUtils.class.getClassLoader()
                .getResourceAsStream("druid.properties");
        try {
            properties.load(is);
            // 2、初始化連接池對象
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //3、對外提供一個方法獲取連接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    //5、對外提供一個獲取連接池對象的方法。
    public static DataSource getDataSource(){
        return ds;
    }
    //4、對外提供一個方法釋放資源
    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 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.JdbcTemplate工具類

2.1 JdbcTemplate執行增、刪、改操作

  • JdbcTemplate介紹
    JdbcTemplate是Spring框架給我們提供的一個簡化jdbc操作的工具類,封裝了增刪改查的操作。
  • 實現步驟
前提:導入相關的開發jar包(5個)+mysql驅動jar包(有就不需要了)+連接池jar包(有就不需要了)
1、創建JdbcTemplate對象
2、調用update(String sql,Object... 代替?的參數值 )方法。
  • 代碼示例
public class JdbcTemplateDMLTest {
  //1. 修改1號數據的 salary 爲 10000
  @Test
  public void testUpdate(){
    //1、創建JdbcTemplate對象
    JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
    //2、調用update(String sql,Object... 代替?的參數值 )方法。
    int count = template.update("update emp set salary=10000 where id=?", 1001);
    System.out.println("count = " + count);
  }
  //2. 添加一條記錄
  @Test
  public void testAdd(){
    //1、創建JdbcTemplate對象
    JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
    //2、調用update(String sql,Object... 代替?的參數值 )方法。
    String sql="insert into emp values(null,?,?,?,?,?,?,?)";
    int count = template.update(sql, "楊鋅怒", 3, 1006, "2000-12-17", 20000, null, 30);
    System.out.println("count = " + count);
  }

  //3. 刪除剛纔添加的記錄
  @Test
  public void testDelete(){
    //1、創建JdbcTemplate對象
    JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
    // 2、調用update(String sql,Object... 代替?的參數值 )方法。
    int count = template.update("delete from emp where id=?", 1015);
    System.out.println("count = " + count);
  }
}

2.2 JdbcTemplate執行查詢操作

  • 實現步驟
前提:導入相關的開發jar包(5個)+mysql驅動jar包(有就不需要了)+連接池jar包(有就不需要了)
1、創建JdbcTemplate對象
2、調用query()或者queryForObject()方法
  • 查詢多條數據–多行多列,封裝成自定義java對象
//6. 查詢所有記錄,將其封裝爲Emp對象的List集合 重點
@Test
public void test4(){
  //1、創建JdbcTemplate對象
  JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
  //2 調用query方法
  List<Emp> list = template.query("select * from emp", new BeanPropertyRowMapper<Emp>(Emp.class));
  for (Emp emp : list) {
    System.out.println(emp);
  }
}
  • 查詢一條數據–單行多列,封裝成一個自定義的java對象,異常要try…catch
//8. 查詢id爲1001的記錄,將其封裝爲Emp集合  重點
@Test
public void test6(){
  //1、創建JdbcTemplate對象
  JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
  //2、調用queryForObject
  Emp emp = null;
  try {
    emp = template.queryForObject("select * from emp where id=?",new BeanPropertyRowMapper<Emp>(Emp.class), 1001);
  } catch (DataAccessException e) {
    e.printStackTrace();
  }
  System.out.println(emp);
}
  • 查詢多條數據–多行單列,指定要存入的集合的泛型類型
//9 查詢每一個用戶的姓名,多行單例 結果肯定是list集合
@Test
public void test7(){
  //1、創建JdbcTemplate對象
  JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
  //2 調用
  List<String> list = template.queryForList("select ename from emp", String.class);
  for (String s : list) {
    System.out.println(s);
  }
}
  • 查詢一條數據–單行單列,這個值是什麼類型就是用什麼類型的Class來封裝
//7. 查詢總記錄數 select count(*) from emp;  單行單列 14
@Test
public void test5(){
  //1、創建JdbcTemplate對象
  JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
  //2、調用queryForObject()
  Integer count = template.queryForObject("select count(*) from emp", Integer.class);
  System.out.println(count);
}

總結

1、連接池
	共講解了c3p0和druid兩個連接池,這兩個連接池的使用都需要配置文件。
	核心:將druid連接池封裝到JDBCUtils工具類中。
	public class JDBCUtils{  //重點
		private static DataSource ds;
    static{
      //加載配置文件
      //1 創建Properties對象
      Properties properties=new Properties();
      //2 調用load方法加載配置文件
      InputStream is
  =JDBCUtils.class.getClassLoader().getResourcesAsStream("druid.properties");
      properties.load(is)
      //初始化druid連接池對象
      ds=DruidDataSourceFactory.createDataSource(properties);
    }
    //5、對外提供一個獲取連接池對象的方法。
    public static DataSource getDataSource(){
      return ds;
    }
	}
2、JdbcTemplate工具類
	增刪改思路:
		1 創建JdbcTemplate對象,需要傳遞連接池對象。
			JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
		2 調用update(String sql,Object... args)方法
			int count=template.update("delete from account where id=?",1);	
	查詢:
		1 創建JdbcTemplate對象,需要傳遞連接池對象。
			JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
		2 調用query(String sql,RowMapper<T> rowMapper,Object... args)或者queryForObject(String sql,RowMapper<T> rowMapper,Object... args)方法。
		重點是多列需要使用自定義Java對象封裝。例如:
		List<Emp> list = template.query("select * from emp", new BeanPropertyRowMapper<Emp>(Emp.class));
		emp = template.queryForObject("select * from emp where id=?",new BeanPropertyRowMapper<Emp>(Emp.class), 1001);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章