Java执行SQL脚本文件到数据库

来源:https://blog.csdn.net/qq_32444825/article/details/87884753?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control

方式一:直接读取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;
        }
    }

复制代码

 加载的SQL文件不在class下

复制代码

   /**
     * @param sqlPath
     */
    public void runsqlBySpringUtils(String sqlPath) {
        try {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Connection conn = sqlSession.getConnection();
            
            FileSystemResource rc = new FileSystemResource(sqlPath);
            EncodedResource er = new EncodedResource(rc, "GBK");
            ScriptUtils.executeSqlScript(conn, er);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

复制代码

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

 方法(2)解决了方法(1)的问题

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值