PreparedStatement
PreparedStatement介面是Statement的子介面,它表示一條預編譯過的SQL陳述句
什么是SQL注入
SQL注入是利用某些系統沒有對用戶輸入的資料進行充分的檢查,而在用戶輸入資料中注入非法的SQL陳述句段或命令,從而利用系統的SQL引擎完成惡意行為的做法,
preparedstatement和statement的區別
PreparedStatement:
PreparedStatement是java.sql包下面的一個介面,用來執行SQL陳述句查詢,通過呼叫connection.preparedStatement(sql)方法可以獲得PreparedStatment物件,資料庫系統會對sql陳述句進行預編譯處理(如果JDBC驅動支持的話),預處理陳述句將被預先編譯好,這條預編譯的sql查詢陳述句能在將來的查詢中重用,這樣一來,它比Statement物件生成的查詢速度更快,
Statement
使用 Statement 物件,在對資料庫只執行一次性存取的時侯,用 Statement 物件進行處理,PreparedStatement 物件的開銷比Statement大,對于一次性操作并不會帶來額外的好處,
Why?為什么要用它??
使用PreparedStatement:是Statement的子介面,可以傳入帶占位符的SQL陳述句,提供了補充占位符變數的方法,
PreparedStatement ps=conn.preparedStatement(sql);
可以看到將sql作為引數傳入了,就不需要我們在費力拼寫了,
變成了這樣的形式
String sql="insert into examstudent values(?,?,?,?,?,?,?)";
如何使用??
建立連接
connection = JDBCUtil.getConnection();
寫SQL陳述句
String sql = "select * from account where username = ? and password = ?";
創建preparedStatement物件預編譯
pstmt = connection.prepareStatement(sql);
給占位符賦值(執行引數)
pstmt.setString(1,username); pstmt.setString(2,password);
//寫SQL陳述句 String sql = "select * from user where username = ? and password = ?";
//預編譯 pstmt = conn.prepareStatement(sql);
//占位符賦值 pstmt.setString(1,"aaa"); pstmt.setString(2,"b' or '1' = '1");
執行SQL
ResultSet resultSet1 = pstmt.executeQuery();
案例
修改教師資訊
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JDBCUtil.getConnection();
String sql = "update teacher set name = ? where id = ?";
// 預編譯
pstmt = conn.prepareStatement(sql);
// 給占位符賦值,根據位置
pstmt.setString(1,"JJ");
pstmt.setInt(2,6);
// 正式執行sql
int i = pstmt.executeUpdate();
System.out.println(i);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil.close(conn,pstmt);
}
}
總結
關于PreparedStatement介面,需要重點記住的是:
1. PreparedStatement可以寫引數化查詢,比Statement能獲得更好的性能,
2. 對于PreparedStatement來說,資料庫可以使用已經編譯過及定義好的執行計劃,這種預處理陳述句查詢比普通的查詢運行速度更快,
3. PreparedStatement可以阻止常見的SQL注入式攻擊,
4. PreparedStatement可以寫動態查詢陳述句
5. PreparedStatement與java.sql.Connection物件是關聯的,一旦你關閉了connection,PreparedStatement也沒法使用了,
6. “?” 叫做占位符,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/502504.html
標籤:MySQL
上一篇:StoneDB社區答疑第一期
