防止SQL注入的方法有:
1.采用PreparedStatement进行预编译,sql语句在执行的过程中效率比Statement要高,例如:
String sql = "select* from users where username=? and password=?";
Connection conn = null;
PreparedStatement state = null;
ResultSet result;
conn = JdbcUtil.getConnection();
System.out.println(sql);
try {
state = conn.prepareStatement(sql);
state.setString(1, userName);
state.setString(2, passWord);
result = state.executeQuery();
2.使用正则表达式过滤传入的参数,例如:
要引入的包:
import java.util.regex.*;
正则表达式:
private String CHECKsql = “^(.+)\\sand\\s(.+)|(.+)\\sor(.+)\\s$”;
判断是否匹配:
Pattern.matches(CHECKsql,targerStr);
3.对字符串进行过滤,例如:
public static boolean sql_inj(String str)
{
String inj_str = "'|and|exec|insert|select|delete|update|
count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";
String inj_stra[] = split(inj_str,"|");
for (int i=0 ; i < inj_stra.length ; i++ )
{
if (str.indexOf(inj_stra[i])>=0)
{
return true;
}
}
return false;
}
4.使用javascript在客户端进行不安全字符屏蔽,例如JSP页面判断代码:
function check(a){return 1;
fibdn = new Array (”‘” ,”\\”,”/”);
i=fibdn.length;
j=a.length;
for (ii=0; ii<i; ii++)
{ for (jj=0; jj<j; jj++)
{ temp1=a.charAt(jj);
temp2=fibdn[ii];
if (tem’; p1==temp2)
{ return 0; }
}
}
return 1;
}