jdbc 系列文章列表, 请查看目录: 《jdbc学习笔记》
Statement 用法比较简单, 不需要设置参数. 创建了Statment对象之后, 直接执行sql即可. 执行步骤可总结如下:
获取数据库连接创建Statment对象执行sql 增删改: 执行executeUpdate(sql)方法, 返回sql影响的行数查询: 执行executeQuery(sql)方法, 返回查询结果ResultSet, 然后解析结果集 public void template(String id){ // 1. 获取数据库连接, 自动提交事务 Connection connection = DbConnUtil.getConnection(); Statement statement = null; try { // 2.获取PreparedStatement, 并设置需要回填主键 statement = connection.createStatement(); // 3.执行增删改sql statement.executeUpdate("delete ...."); // 3.执行查询sql ResultSet rs = statement.executeQuery(""); } catch (SQLException e) { e.printStackTrace(); }finally { // 4.释放资源 DbConnUtil.release(statement, connection); } }众所周知, jdbc 的Statement 是一个不安全的API ,容易产生sql 注入风险. 笔者来模拟一下sql注入的原理.
定义通过id 删除的方法, 笔者为了测试sql注入, id类型替换为String.
public int deleteById(String id){ String sql = "delete from t_user where id ='" + id + "'"; System.out.println("执行sql:" + sql); // 1. 获取数据库连接, 自动提交事务 Connection connection = DbConnUtil.getConnection(); Statement statement = null; try { // 2.获取PreparedStatement, 并设置需要回填主键 statement = connection.createStatement(); // 3.执行sql return statement.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); }finally { // 5.释放资源 DbConnUtil.release(statement, connection); } return 0; }id不仅仅传递一个数值, 而是拼接一个or 1=1 的条件, 那么就会清空整个表的数据.
@Test public void test1(){ // 拼接注入sql String id = "1' or '1'='1"; int cnt = deleteById(id); System.out.println("删除行数:" + cnt); }