1.采用预编译语句集,它内置了处理SQL注入的能力,只要使用它的setString方法传值即可:
String sql= "select * from users where username=? and password=?; PreparedStatement preState = conn.prepareStatement(sql); preState.setString(1, userName); preState.setString(2, password); ResultSet rs = preState.executeQuery();
2.采用正则表达式将包含有 单引号('),分号(;) 和 注释符号(--)的语句给替换掉来防止SQL注入
public static String SQL(String str) { return str.replaceAll(".*([';]+|(--)+).*", " "); } userName=SQL(userName); password=SQL(password); String sql="select * from users where username='"+userName+"' and password='"+password+"' " Statement sta = conn.createStatement(); ResultSet rs = sta.executeQuery(sql);