第一种采用预编译语句集,它内置了处理SQL注入的能力,只要使用它的setString方法传值即可:

 

Java代码 JAVA程序防止SQL注入的方法 _的 JAVA程序防止SQL注入的方法 _的_02
  1. String sql= "select * from users where username=? and password=?;
  2. PreparedStatement preState = conn.prepareStatement(sql);
  3. preState.setString(1, userName);
  4. preState.setString(2, password);
  5. ResultSet rs = preState.executeQuery();

第二种是采用正则表达式将包含有 单引号('),分号(;) 和 注释符号(--)的语句给替换掉来防止SQL注入:

 

Java代码 JAVA程序防止SQL注入的方法 _的 JAVA程序防止SQL注入的方法 _的_02
  1. public static String TransactSQLInjection(String str)
  2. {
  3. return str.replaceAll(".*([';]+|(--)+).*", " ");
  4. }
  5.  
  6. userName=TransactSQLInjection(userName);
  7. password=TransactSQLInjection(password);
  8.  
  9. String sql="select * from users where username='"+userName+"' and password='"+password+"' "
  10. Statement sta = conn.createStatement();
  11. ResultSet rs = sta.executeQuery(sql);

 

安全性:Java只要使用PreparedStatement,就不会存在注入问题。至今还没遇到用了PreparedStatement还会被注入的情况。