MySQL數(shù)據(jù)庫干貨_27——PreparedStatement的使用(重點(diǎn))
PreparedStatement的使用(重點(diǎn))
PreparedStatement對象簡介
繼承自 Statement 接口,由 preparedStatement方法創(chuàng)建。PreparedStatement具有預(yù)編譯SQL語句能力,所以PreparedStatement 對象比 Statement 對象的效率更高,由于實(shí)現(xiàn)了動態(tài)的參數(shù)綁定,所以可以防止 SQL 注入,所以我們一般都使用 PreparedStatement。
PreparedStatement對象的特點(diǎn):
- PreparedStatement 接口繼承 Statement 接口
- PreparedStatement 效率高于 Statement
- PreparedStatement 支持動態(tài)綁定參數(shù)
- PreparedStatement 具備 SQL 語句預(yù)編譯能力
- 使用 PreparedStatement 可防止出現(xiàn) SQL 注入問題
PreparedStatement 的預(yù)編譯能力
語句的執(zhí)行步驟
- 語法和語義解析
- 優(yōu)化 sql 語句,制定執(zhí)行計(jì)劃
- 執(zhí)行并返回結(jié)果
但是很多情況,我們的一條 sql 語句可能會反復(fù)執(zhí)行,或者每次執(zhí)行的時候只有個別的值不同(比如 select 的 where 子句值不同,update 的 set 子句值不同,insert 的 values 值不同)。 如果每次都需要經(jīng)過上面的詞法語義解析、語句優(yōu)化、制定執(zhí)行計(jì)劃等,則效率就明顯不行 了。所謂預(yù)編譯語句就是將這類語句中的值用占位符替代,可以視為將 sql 語句模板化或者說參數(shù)化預(yù)編譯語句的優(yōu)勢在于:一次編譯、多次運(yùn)行,省去了解析優(yōu)化等過程;此外預(yù)編譯語 句能防止 sql 注入
通過PreparedStatement添加數(shù)據(jù)
/**
* PreparedStatement使用的測試類
*/
public class PreparedStatementTest {
/**
* 添加用戶
*/
public void insertUsers(String username,int userage){
Connection connection = null;
PreparedStatement ps = null;
try{
//獲取數(shù)據(jù)庫連接
connection = JdbcUtils.getConnection();
//定義Sql。?是PreparedStatement對象中的綁定參數(shù)的占位符。問號的位置是從1開始計(jì)數(shù)的
String sql = "insert into users values(default,?,?)";
//創(chuàng)建PreparedStatement對象
ps = connection.prepareStatement(sql);
//完成參數(shù)的綁定
ps.setString(1,username);
ps.setInt(2,userage);
int i = ps.executeUpdate();
System.out.println(i);
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtils.closeResource(ps,connection);
}
}
}
通過PreparedStatement修改數(shù)據(jù)
/**
* 通過PreparedStatement對數(shù)據(jù)庫表更新數(shù)據(jù)
*/
public void updateByUserId(int userid,String username,int userage){
Connection connection=null;
PreparedStatement preparedStatement=null;
try{
//獲取數(shù)據(jù)庫連接
connection=JdbcUtils.getConnection();
//獲取PreparedStatement對象
preparedStatement=connection.prepareStatement("update users set userName=?,userAge=? where userid=?");
//對參數(shù)進(jìn)行動態(tài)綁定
preparedStatement.setString(1,username);
preparedStatement.setInt(2,userage);
preparedStatement.setInt(3,userid);
//執(zhí)行sql語句
int i = preparedStatement.executeUpdate();
System.out.println(i);
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils.closeResource(preparedStatement,connection);
}
}
通過PreparedStatement刪除數(shù)據(jù)
/**
* 根據(jù)用戶ID刪除指定用戶
*/
public void deleteUsersById(int userid){
Connection conn = null;
PreparedStatement ps = null;
try{
//獲取數(shù)據(jù)庫連接對象
conn = JdbcUtils.getConnection();
//創(chuàng)建PreparedStatement對象
ps = conn.prepareStatement("delete from users where userid = ? ");
//綁定參數(shù)
ps.setInt(1,userid);
int i = ps.executeUpdate();
System.out.println(i);
}catch (Exception e){
e.printStackTrace();
}finally{
JdbcUtils.closeResource(ps,conn);
}
}
浙公網(wǎng)安備 33010602011771號