温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Java如何将SQL脚本文件执行到数据库中

发布时间:2020-11-24 17:06:32 来源:亿速云 阅读:815 作者:Leah 栏目:编程语言

使用Java如何将SQL脚本文件执行到数据库中?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

方式一:直接读取SQL脚本文件的内容,然后传递到SQL中。

代码:RunSqlService:

  @Autowired
  private RunSqlDao runSqlDao;
  
  /**
   * 读取文件内容到SQL中执行
   * @param sqlPath SQL文件的路径:如:D:/TestProject/web/sql/脚本.Sql
   */
  public void runSqlByReadFileContent(String sqlPath) throws Exception {
    try {
       
      String sqlStr = readFileByLines(sqlPath);
      // System.out.println("获得的文本:" + sqlStr);
      if (sqlStr.length() > 0) {
        runSqlDao.runSqlBySqlStr(sqlStr);
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
  
  /**
   * 以行为单位读取文件,常用于读面向行的格式化文件
   */
  private String readFileByLines(String filePath) throws Exception {
    StringBuffer str = new StringBuffer();
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new InputStreamReader(
          new FileInputStream(filePath), "UTF-8"));
      String tempString = null;
      int line = 1;
      // 一次读入一行,直到读入null为文件结束
      while ((tempString = reader.readLine()) != null) {
        // 显示行号
        // System.out.println("line " + line + ": " + tempString);

        str = str.append(" " + tempString);
        line++;
      }
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
      throw e;
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e1) {
        }
      }
    }

    return str.toString();
  }

RunSqlDao : 

  /**
   * @param sqlStr
   */
  public void runSqlBySqlStr(String sqlStr) {
    Map<String,Object> map=new HashMap<String,Object>();
    map.put("sqlStr", sqlStr);
    sqlSessionTemplate.selectList("runSql.runSqlBySqlStr", map);
  }

SQLMap:

<mapper namespace="runSql">

<select id="runSqlBySqlStr" parameterType="map">
<![CDATA[ ${sqlStr}]]>
</select>

</mapper>

这种写法:只支持数据的变化(新增、修改、删除),且SQL文件内容以begin开始,以end结束。无法更新表字段修改等操作。

方式二;使用ScriptRunner

代码:RunSqlService:

  /**
   * 执行sql脚本文件 使用ScriptRunner
   * @param sqlPath SQL文件的路径:如:D:/TestProject/web/sql/脚本.Sql
   */
  public void runSqlByScriptRunner(String sqlPath) throws Exception {
    try {
      SqlSession sqlSession = sqlSessionFactory.openSession();
      Connection conn = sqlSession.getConnection();
      ScriptRunner runner = new ScriptRunner(conn);
      runner.setEscapeProcessing(false);
      runner.setSendFullScript(true);      
      runner.runScript(new InputStreamReader(new FileInputStream(sqlPath), "UTF-8"));
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }


这种写法:只能有一行SQL,即一次执行一个SQL语句,否则就会报错。

方式三:使用ScriptUtils

代码:RunSqlService:(以下两种方式:脚本.Sql 和RunSqlService 在同一目录下)

方法(1)

  /**
   * 执行sql脚本文件 使用Spring工具类
   */
  public void runSqlBySpringUtils() throws Exception {
    try {
      SqlSession sqlSession = sqlSessionFactory.openSession();
      Connection conn = sqlSession.getConnection();
      ClassPathResource rc = new ClassPathResource("脚本.Sql", RunSqlDao.class);
      ScriptUtils.executeSqlScript(conn, rc);
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

方法(2)

  /**
   * 执行sql脚本文件 使用Spring工具类
   */
  public void runSqlBySpringUtils() throws Exception {
    try {
      SqlSession sqlSession = sqlSessionFactory.openSession();
      Connection conn = sqlSession.getConnection();
      ClassPathResource rc = new ClassPathResource("脚本.Sql", RunSqlDao.class);
      EncodedResource er = new EncodedResource(rc, "utf-8");
      ScriptUtils.executeSqlScript(conn, er);
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

方法(1),脚本.Sql文件必须是ANSI的,否则执行到数据中汉字是乱码。

方法(2)解决了方法(1)的问题,完美了,喜欢的小伙伴们快拿去享用吧。

关于使用Java如何将SQL脚本文件执行到数据库中问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI