【MyBatis源码】ScriptRunner工具分析-基础使用

【1】执行外部SQL脚本

  @Test
  public void test1() {
    try {
      // 数据库连接
      Connection connection =
        DriverManager.getConnection("jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "root");
      // 创建ScriptRunner对象
      ScriptRunner scriptRunner = new ScriptRunner(connection);
      // 读取classpath路径下的文件,返回Reader对象
      Reader reader = Resources.getResourceAsReader("sql/test_ddl.sql");
      // 执行SQL脚本
      scriptRunner.runScript(reader);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

在这里插入图片描述
【2】执行 insert、update、delete、select 等操作。

selectOne(String sql, Object... args):执行SELECT查询语句,返回一条数据;
selectAll(String sql, Object... args):执行SELECT查询语句,返回多条数据;
insert(String sql, Object... args):执行INSERT语句;
update(String sql, Object… args):执行UPDATE语句;
delete(String sql, Object... args):执行DELETE语句;
run(String sql):运行任意一条SQL语句。
            // 示例1:执行查询
            Map<String, Object> result = runner.selectOne("SELECT * FROM user WHERE id = ?", 1);
            System.out.println("查询结果:" + result);

            // 示例2:执行插入
            int rows = runner.insert("INSERT INTO user (name, age) VALUES (?, ?)", "张三", 25);
            System.out.println("插入结果:" + rows);

            // 示例3:执行更新
            rows = runner.update("UPDATE user SET age = ? WHERE name = ?", 30, "张三");
            System.out.println("更新结果:" + rows);

            // 示例4:执行删除
            rows = runner.delete("DELETE FROM user WHERE name = ?", "张三");
            System.out.println("删除结果:" + rows);
上一篇:网络安全应急响应(归纳)-二、理论