回顧下以前jdbc的開發步驟:sql
1:建項目,引入數據庫驅動包數據庫
2:加載驅動緩存
Class.forName(..);spa
3:獲取鏈接對象code
4:建立執行sql語句的stmt對象; 寫sql對象
5:執行sqlblog
a) 更新 delete/insert/update接口
!:executeUpdate(); 開發
b) 查詢 select get
!:executeQuery();
6:關閉/異常
以前有說過,Statement接口和PreparedStatement接口的區別,其中的一個就是:
PreparedStatement接口可以防止sql注入
那麼,什麼是sql注入呢?
其實sql注入就是用戶輸入的惡意密碼,可以繞過你的用戶名和密碼登錄。
例子:
1:首先建立個數據庫
1 -- 建立數據庫 2 CREATE DATABASE jdbc_demo DEFAULT CHARACTER SET utf8;i 3 -- 建立表 4 USE jdbc_demo; 5 CREATE TABLE admin( 6 id INT PRIMARY KEY AUTO_INCREMENT, 7 userName VARCHAR(20), 8 pwd VARCHAR(20) 9 )
2:使用Statement接口,沒有防止sql注入:
1 /** 2 * 模擬用戶登錄數據庫,演示注入 3 * 4 * @author LLZ 5 */ 6 public class Two_StatementDemo { 7 8 /** 9 * 1:sql注入 Statement 10 */ 11 12 private Connection conn; 13 private Statement stsm; 14 private ResultSet rs; 15 private PreparedStatement pstsm; 16 17 @Test 18 public void Test1() { 19 20 String user = "tom"; 21 // String password = "123"; 22 String password = " ' or 1=1 -- /**/ "; // sql注入,這個也能夠登錄成功 23 24 try { 25 // 1.1:加載驅動 26 conn = Jdbcutil.getConnection(); 27 28 // 1.3:建立Statement對象 29 stsm = conn.createStatement(); 30 31 // 1.4:準備sql語句 32 String sql = "select * from jdbc where user='" + user 33 + "' and password='" + password + "' "; 34 35 // 1.5:執行sql 36 rs = stsm.executeQuery(sql); 37 38 // 1.6:打印返回的結果 39 if (rs.next()) { 40 System.out.println(rs.getInt("id")); 41 } 42 } catch (Exception e) { 43 e.printStackTrace(); 44 45 } finally { 46 // 1.7:關閉鏈接 47 try { 48 rs.close(); 49 stsm.close(); 50 conn.close(); 51 } catch (Exception e) { 52 53 e.printStackTrace(); 54 } 55 } 56 }
3:使用PreparedStatement接口,防止sql注入:
其緣由就是因爲該接口具備緩存區,須要先執行預編譯遠,等傳入參數才正式執行sql語言
1 /** 2 * 二:用PreparedStatement防止sql注入 3 */ 4 @Test 5 public void Test2() { 6 7 String user = "tom"; 8 String password = "123"; 9 // String password = " ' or 1=1 -- /**/ "; // sql注入,這個在這裏就沒法登錄 10 // 準備sql預編譯語句 11 String sql = "select * from jdbc where user=? and password=?"; 12 13 try { 14 // 2.1:建立鏈接 15 conn = Jdbcutil.getConnection(); 16 17 // 2.2:建立PerparedStatement對象(執行預編譯) 18 pstsm = conn.prepareStatement(sql); 19 20 // 2.3:準備參數 21 pstsm.setString(1, user); 22 pstsm.setString(2, password); 23 24 // 2.4:發送參數,執行sql 25 ResultSet rs = pstsm.executeQuery(); 26 if (rs.next()) { 27 System.out.println(rs.getInt("id")); 28 } 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } finally { 32 // 2.5:關閉鏈接 33 Jdbcutil.close(conn, pstsm, rs); 34 } 35 36 }