JDBC與JDBC連接池聽課筆記

實現JDBC的基本步驟

	* 步驟:
		1. 導入驅動jar包 mysql-connector-java-5.1.37-bin.jar
			1.複製mysql-connector-java-5.1.37-bin.jar到項目的libs目錄下
			2.右鍵-->Add As Library
		2. 註冊驅動
		3. 獲取數據庫連接對象 Connection
		4. 定義sql
		5. 獲取執行sql語句的對象 Statement
		6. 執行sql,接受返回結果
		7. 處理結果
		8. 釋放資源
	* 代碼實現:
	  	//1. 導入驅動jar包
        //2.註冊驅動
        Class.forName("com.mysql.jdbc.Driver");
        //3.獲取數據庫連接對象
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "root");
        //4.定義sql語句
        String sql = "update account set balance = 500 where id = 1";
        //5.獲取執行sql的對象 Statement
        Statement stmt = conn.createStatement();
        //6.執行sql
        int count = stmt.executeUpdate(sql);
        //7.處理結果
        System.out.println(count);
        //8.釋放資源
        stmt.close();
        conn.close();

JDBC控制事務:

1. 事務:一個包含多個步驟的業務操作。如果這個業務操作被事務管理,則這多個步驟要麼同時成功,要麼同時失敗。
2. 操作:
	1. 開啓事務
	2. 提交事務
	3. 回滾事務
3. 使用Connection對象來管理事務
	* 開啓事務:setAutoCommit(boolean autoCommit) :調用該方法設置參數爲false,即開啓事務
		* 在執行sql之前開啓事務
	* 提交事務:commit() 
		* 當所有sql都執行完提交事務
	* 回滾事務:rollback() 
		* 在catch中回滾事務

4. 代碼:
public class JDBCDemo10 {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;

        try {
            //1.獲取連接
            conn = JDBCUtils.getConnection();
            //開啓事務
            conn.setAutoCommit(false);

            //2.定義sql
            //2.1 張三 - 500
            String sql1 = "update account set balance = balance - ? where id = ?";
            //2.2 李四 + 500
            String sql2 = "update account set balance = balance + ? where id = ?";
            //3.獲取執行sql對象
            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);
            //4. 設置參數
            pstmt1.setDouble(1,500);
            pstmt1.setInt(2,1);

            pstmt2.setDouble(1,500);
            pstmt2.setInt(2,2);
            //5.執行sql
            pstmt1.executeUpdate();
            // 手動製造異常
            int i = 3/0;

            pstmt2.executeUpdate();
            //提交事務
            conn.commit();
        } catch (Exception e) {
            //事務回滾
            try {
                if(conn != null) {
                    conn.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JDBCUtils.close(pstmt1,conn);
            JDBCUtils.close(pstmt2,null);
        }
    }
}

數據庫連接池

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:查詢結果,將結果封裝爲對象
			* 一般用於聚合函數的查詢
  1. 練習:
    需求:
    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);
    }

}

JDBCUtils.java

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class JDBCUtils {
	//新建DataSource成員變量
	private static DataSource ds;
	/**
	 * 它爲null表示沒有事務
	 * 它不爲null表示有事務
	 * 當開啓事務時,需要給它賦值
	 * 當結束事務時,需要給它賦值爲null
	 * 並且在開啓事務時,讓dao的多個方法共享這個Connection
	 */
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	//靜態代碼塊初始化ds
	static {
		try {
			//獲取配置文件
			Properties pro =new Properties();
			pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
			//初始化
			ds = DruidDataSourceFactory.createDataSource(pro);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//獲取鏈接
	public static Connection getConnection() throws SQLException {
		/*
		 * 如果有事務,返回當前事務的con
		 * 如果沒有事務,通過連接池返回新的con
		 */
		Connection con = tl.get();//獲取當前線程的事務連接
		if(con != null) return con;
		return ds.getConnection();
	}
	/**
	 * 開啓事務
	 * @throws SQLException 
	 */
	public static void beginTransaction() throws SQLException {
		Connection con = tl.get();//獲取當前線程的事務連接
		if(con != null) throw new SQLException("已經開啓了事務,不能重複開啓!");
		con = ds.getConnection();//給con賦值,表示開啓了事務
		con.setAutoCommit(false);//設置爲手動提交
		tl.set(con);//把當前事務連接放到tl中
	}
	
	/**
	 * 提交事務
	 * @throws SQLException 
	 */
	public static void commitTransaction() throws SQLException {
		Connection con = tl.get();//獲取當前線程的事務連接
		if(con == null) throw new SQLException("沒有事務不能提交!");
		con.commit();//提交事務
		con.close();//關閉連接
		con = null;//表示事務結束!
		tl.remove();
	}
	
	/**
	 * 回滾事務
	 * @throws SQLException 
	 */
	public static void rollbackTransaction() throws SQLException {
		Connection con = tl.get();//獲取當前線程的事務連接
		if(con == null) throw new SQLException("沒有事務不能回滾!");
		con.rollback();
		con.close();
		con = null;
		tl.remove();
	}
	
	/**
	 * 釋放Connection
	 * @param con
	 * @throws SQLException 
	 */
	public static void releaseConnection(Connection connection) throws SQLException {
		Connection con = tl.get();//獲取當前線程的事務連接
		if(connection != con) {//如果參數連接,與當前事務連接不同,說明這個連接不是當前事務,可以關閉!
			if(connection != null &&!connection.isClosed()) {//如果參數連接沒有關閉,關閉之!
				connection.close();
			}
		}
	}
	
	//釋放資源
	public static void close(Statement st,Connection conn) {
		close(null,st,conn);
	}
	
	public static void close(ResultSet rs,Statement st,Connection conn) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(st!=null) {
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			releaseConnection(conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

標題

public static void main(String[] args){
		Connection con = null;
		PreparedStatement psmt1 =null;
		PreparedStatement psmt2 =null;
		ResultSet rs= null;
		try {
			JDBCUtils.beginTransaction();
			con = JDBCUtils.getConnetion();
			psmt1 = con.prepareStatement("update admin Set uid = '5' where username =?");
			psmt2 = con.prepareStatement("update admin Set uid = '6' where username =?");
			psmt1.setString(1, "ceshi2");
			psmt2.setString(1, "ceshi3");
			psmt1.execute();
			psmt2.execute();
			JDBCUtils.commitTransaction();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				JDBCUtils.rollbackTransaction();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} finally {
			JDBCUtils.close(psmt1,con);
			JDBCUtils.close(psmt2,con);
		}
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章