04-JDBC基礎

目錄

概述

快速入門


概述

Java DataBase Connectivity  Java 數據庫連接, Java語言操作數據庫
JDBC本質:其實是官方(sun公司)定義的一套操作所有關係型數據庫的規則,即接口。

各個數據庫廠商去實現這套接口,提供數據庫驅動jar包。可以使用這套接口(JDBC)編程,真正執行的代碼是驅動jar包中的實現類。

快速入門

步驟:

 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/db3", "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();

詳解各個對象

1. DriverManager:驅動管理對象
   功能:
		1. 註冊驅動:告訴程序該使用哪一個數據庫驅動jar
			static void registerDriver(Driver driver) :註冊與給定的驅動程序 DriverManager 。 
			寫代碼使用:  Class.forName("com.mysql.jdbc.Driver");
			通過查看源碼發現:在com.mysql.jdbc.Driver類中存在靜態代碼塊
			 static {
			        try {
			            java.sql.DriverManager.registerDriver(new Driver());
			        } catch (SQLException E) {
			            throw new RuntimeException("Can't register driver!");
			        }
				}

			注意:mysql5之後的驅動jar包可以省略註冊驅動的步驟。
		2. 獲取數據庫連接:
			* 方法:static Connection getConnection(String url, String user, String password) 
			* 參數:
				* url:指定連接的路徑
					* 語法:jdbc:mysql://ip地址(域名):端口號/數據庫名稱
					* 例子:jdbc:mysql://localhost:3306/db3
					* 細節:如果連接的是本機mysql服務器,並且mysql服務默認端口是3306,則url可以簡寫爲:jdbc:mysql:///數據庫名稱
				* user:用戶名
				* password:密碼 
2. Connection:數據庫連接對象
	1. 功能:
		1. 獲取執行sql 的對象
			* Statement createStatement()
			* PreparedStatement prepareStatement(String sql)  
		2. 管理事務:
			* 開啓事務:setAutoCommit(boolean autoCommit) :調用該方法設置參數爲false,即開啓事務
			* 提交事務:commit() 
			* 回滾事務:rollback() 
3. Statement:執行sql的對象
	1. 執行sql
		1. boolean execute(String sql) :可以執行任意的sql 瞭解 
		2. int executeUpdate(String sql) :執行DML(insert、update、delete)語句、DDL(create,alter、drop)語句
			* 返回值:影響的行數,可以通過這個影響的行數判斷DML語句是否執行成功 返回值>0的則執行成功,反之,則失敗。
		3. ResultSet executeQuery(String sql)  :執行DQL(select)語句
	2. 練習:
		1. account表 添加一條記錄
		2. account表 修改記錄
		3. account表 刪除一條記錄

		代碼:
			Statement stmt = null;
	        Connection conn = null;
	        try {
	            //1. 註冊驅動
	            Class.forName("com.mysql.jdbc.Driver");
	            //2. 定義sql
	            String sql = "insert into account values(null,'王五',3000)";
	            //3.獲取Connection對象
	            conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");
	            //4.獲取執行sql的對象 Statement
	            stmt = conn.createStatement();
	            //5.執行sql
	            int count = stmt.executeUpdate(sql);//影響的行數
	            //6.處理結果
	            System.out.println(count);
	            if(count > 0){
	                System.out.println("添加成功!");
	            }else{
	                System.out.println("添加失敗!");
	            }
	
	        } catch (ClassNotFoundException e) {
	            e.printStackTrace();
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }finally {
	            //stmt.close();
	            //7. 釋放資源
	            //避免空指針異常
	            if(stmt != null){
	                try {
	                    stmt.close();
	                } catch (SQLException e) {
	                    e.printStackTrace();
	                }
	            }
	
	            if(conn != null){
	                try {
	                    conn.close();
	                } catch (SQLException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
		
4. ResultSet:結果集對象,封裝查詢結果
	* boolean next(): 遊標向下移動一行,判斷當前行是否是最後一行末尾(是否有數據),如果是,則返回false,如果不是則返回true
	* getXxx(參數):獲取數據
		* Xxx:代表數據類型   如: int getInt() ,	String getString()
		* 參數:
			1. int:代表列的編號,從1開始   如: getString(1)
			2. String:代表列名稱。 如: getDouble("balance")
	
	* 注意:
		* 使用步驟:
			1. 遊標向下移動一行
			2. 判斷是否有數據
			3. 獲取數據

		   //循環判斷遊標是否是最後一行末尾。
            while(rs.next()){
                //獲取數據
                //6.2 獲取數據
                int id = rs.getInt(1);
                String name = rs.getString("name");
                double balance = rs.getDouble(3);

                System.out.println(id + "---" + name + "---" + balance);
            }

				
5. PreparedStatement:執行sql的對象
	1. SQL注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接。會造成安全性問題
		1. 輸入用戶隨便,輸入密碼:a' or 'a' = 'a
		2. sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a' 

	2. 解決sql注入問題:使用PreparedStatement對象來解決
	3. 預編譯的SQL:參數使用?作爲佔位符
	4. 步驟:
		1. 導入驅動jar包 mysql-connector-java-5.1.37-bin.jar
		2. 註冊驅動
		3. 獲取數據庫連接對象 Connection
		4. 定義sql
			* 注意:sql的參數使用?作爲佔位符。 如:select * from user where username = ? and password = ?;
		5. 獲取執行sql語句的對象 PreparedStatement  Connection.prepareStatement(String sql) 
		6. 給?賦值:
			* 方法: setXxx(參數1,參數2)
				* 參數1:?的位置編號 從1 開始
				* 參數2:?的值
		7. 執行sql,接受返回結果,不需要傳遞sql語句
		8. 處理結果
		9. 釋放資源

	5. 注意:後期都會使用PreparedStatement來完成增刪改查的所有操作
		1. 可以防止SQL注入
		2. 效率更高

 

SQL注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接。會造成安全性問題
        1. 輸入用戶隨便,輸入密碼:a' or 'a' = 'a
        2. sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a' 

解決sql注入問題:使用PreparedStatement對象來解決
預編譯的SQL:參數使用?作爲佔位符

 

 

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);
	        }
	
	
	    }
	
	}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章