Java 执行SQL脚本文件

  • 读取sql脚本文件时,需要通过ClassPathResource 来获取(其他方式服务器发布后可能会出现无法获取脚本的情况)
  • 根据上步获取的inputStream 流创建InputStreamReader
  • 根据Connection信息初始化创建ScriptRunner ,并执行
	private void execute(String url, String rootName, String rootPwd, String dbName, String userName, String password, String port) {
        String connectUrl = "jdbc:mysql://" + url + ":" + port + "/?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=true";
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(connectUrl, rootName, rootPwd);
	        initTable(connection);
        } catch (SQLException | ClassNotFoundException | IOException e) {
            // 异常处理
           
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    // 异常处理
                }
            }
        }
    }
 
    private void initTable(Connection connection) throws IOException {
        // sql 脚本
        ClassPathResource classPathResource = new ClassPathResource("sql/initTable.sql");
        InputStream inputStream = classPathResource.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        ScriptRunner scriptRunner = new ScriptRunner(connection);
        // 必须设置该参数为true,否则无法执行begin……end;
        scriptRunner.setSendFullScript(true);
        scriptRunner.runScript(inputStreamReader);
    }

注意:当所要执行的sql脚本中包含begin……end;类的sql语句是,需要设置sendFullScript为true,否则会出现以下错误

Error executing: CREATE PROCEDURE `optimizet_procedure`()
begin
    optimize table task
.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
Error executing: end
.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'end' at line 1
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值