您的位置:首页 > 编程语言 > Java开发

如何解决java.sql.Statement无法处理特殊字符以及容易被黑问题

2017-07-30 14:22 891 查看
知识点:展示java.sql.Statement 有两个缺陷,解决方法

第一个:展示Statement的缺陷1(测试数据:1003 换行 a’s) –即若用户输入sql中的特殊字符则程序会挂)

public void dem04() throws Exception{
Connection con = ConnUtils.getConnection();
Statement st = con.createStatement();
// 假设书名含有特殊符号 '  Statement将无法处理~
String name = "a's";
String sql_insert = "insert into book(name,price,birth) values('"+name+"','105.3','1883-5-6 13:11:11');";
System.out.println(sql_insert);
int n = st.executeUpdate(sql_insert);
con.close();
}


结果失败 含有特殊符号的书名添加失败~



我们输入的SQL语句



第二个:展示Statement的缺陷2(测试数据:aa’ or ‘1’=’1) –即若用户输入sql中的特殊字符则程序会黑进)

public void dem05() throws Exception{
Connection con = ConnUtils.getConnection();
Statement st = con.createStatement();
// 假设书名含有特殊符号 '  Statement将无法处理~
String name = "aa' or '1'='1";
String sql = "select count(*) from stud where sname='"+name+"'";
System.out.println("实际的SQL语句:"+sql);
ResultSet rs = st.executeQuery(sql);
rs.next();
int a = rs.getInt(1);
if(a==0){
System.out.println("登陆失败!!");
}else{
System.out.println("登录成功!!");
}
con.close();
}


结果 数据库不存在的用户登录进去了。



如何解决? 用java.sql.PreparedStatement;

使用方法如下

// 当用户数入的参数时,一定要通过预处理(PreparedStatement)防黑和防止特殊字符
@Test
public void demo6() throws Exception{
Connection con = ConnUtils.getConnection();
//      String sql_insert = "insert into book(name,price,birth) values('"+name+"','105.3','1883-5-6 13:11:11');";
String sql = "insert into book(name,price,birth) values(?,?,?);";
PreparedStatement pst = con.prepareStatement(sql);
//含有特殊字符的书名
String name = "a's";
String price = "37.5";
String birth = "1783-5-6 13:31:11";
//设置三个? (参数)
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, birth);
// 执行的时候不需要再给参数。
pst.execute();
con.close();
}


数据库内部添加特殊字符书名成功



防黑缺陷解决

@Test //同时展示Statement的缺陷2(测试数据:aa' or '1'='1) --即若用户输入sql中的特殊字符则程序会黑进)
public void demo7() throws Exception{
Connection con = ConnUtils.getConnection();
String sql = "select count(*) from stud where sname=?";
//      Statement st = con.createStatement();
PreparedStatement pst = con.prepareStatement(sql);
// 假设书名含有特殊符号 '  Statement将无法处理~
String name = "aa' or '1'='1";
pst.setString(1, name);
//执行时不要再给参数了,否则就调用调用 statement的方法了
ResultSet rs = pst.executeQuery();
rs.next();
int a = rs.getInt(1);
if(a==0){
System.out.println("登陆失败!!");
}else{
System.out.println("登录成功!!");
}
con.close();
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据 sql
相关文章推荐