mysql预编译语句拼接查询_SQL语句预编译(查询)
SQL語句預編譯
SQL語句預編譯能預防SQL注入提高安全性,是因為SQL語句在程序運行前已經進行了預編譯,在程序運行時第一次操作數據庫之前,SQL語句已經被數據庫分析,編譯和優化,對應的執行計劃也會緩存下來并允許數據庫以參數化的形式進行查詢,當運行時動態地把參數傳給PreprareStatement時,即使參數里有敏感字符如 or '1=1'也數據庫會作為一個參數一個字段的屬性值來處理而不會作為一個SQL指令,就起到了SQL注入的作用。
一、加載驅動
Class.forName("com.mysql.jdbc.Driver");//加載驅動
二、建立連接數據庫對象
Connection conn=null;
conn = DriverManager.getConnection("jdbc:mysql:///test","root","root");
三、定義SQL語句,參數為?
String sql="select * from student1 where stunum=?";
四、建立預編譯執行對象
PreparedStatement psm = null;
psm=conn.prepareStatement(sql);
五、設置sql語句中的參數值
psm.setString(1,stuNum);
六、定義結果集,把執行對象的查詢結果放入rs中
ResultSet rs = null;
rs=psm.executeQuery();
七、打印結果
while (rs.next()){
String stunum=rs.getString(1);
String stuname=rs.getString(2);
String stuclass=rs.getString(3);
System.out.println("查詢學生信息如下:");
System.out.println(stunum+" "+stuname+" "+stuclass);
}
八、關閉資源
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (psm!=null){
try {
psm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
總結
以上是生活随笔為你收集整理的mysql预编译语句拼接查询_SQL语句预编译(查询)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python获取当前进程id_从pyth
- 下一篇: 中国四大瓷都 关于中国四大瓷都简介