sql注入小解,以及statement和preparedStatement的理解和区别

SQL注入:

资料:

比如在用户名或密码中[or '1' = '1']


动态 生成 Sql语 句 时 没有 对 用 户输 入的数据 进 行 验证 是 Sql注入 攻 击 得逞的主要原因。  
对 于 JDBC而言, SQL注入 攻 击 只 对 Statement有效, 对 PreparedStatement 是无效的


将 绕过验证 ,但 这种 手段只 对 只 对 Statement有效, 对 PreparedStatement 无效。  
PreparedStatement 相 对 Statement有以下 优 点:  
1.防注入攻击  
2.多次运行速度快     //因为preparestatement会使oracle的存储方案定型,而statement不会,很多持久层框架底层大多用的preparedStatement 我们公司的持久层框架就是如此。
3.防止数据库缓冲区溢出    //不懂.....没理解 还请大家赐教原由
4.代码的可读性可维护性好 


preparedstatement方法执行完后,sql语句会发送给数据库,数据库会对sql进行预编译,预编译后的sql语句的结构是不能改变的。
预编译就是数据库会对sql的结构进行编译,但是不是真正上的编译得到结果集。
即:比如[or '1'='1'] 就是不能作为sql结构 只能作为参数传递了 
否则会将[or '1'='1']将会作为表结构


//正确写法 批处理+防止sql注入
String sql = "insert into employee (name, city, phone) values (?, ?, ?)";
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
 for (Employee employee: employees) {
    ps.setString(1, employee.getName());
    ps.setString(2, employee.getCity());
    ps.setString(3, employee.getPhone());
    ps.addBatch();
}
ps.executeBatch();
ps.close();
connection.close();

//不防止sql注入的写法
Connection connection = new getConnection();
Statement statemenet = connection.createStatement();
for (Employee employee: employees) {
    String query = "insert into employee (name, city) values('"
            + employee.getName() + "','" + employee.getCity + "')";
    statemenet.addBatch(query);
}

statemenet.executeBatch();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值