SQL注入:
动态 生成 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);
}
资料:
比如在用户名或密码中[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();