java逐行读取文件内容执行sql语句_通过Java执行.sql文件

在尝试使用Java逐行读取并执行含有`GO`作为语句分隔符的SQL脚本时遇到问题。通常的解决方案如ScriptRunner不适用于这种格式的脚本。文中提出了一个替代方案,即通过Java启动一个新的数据库客户端进程,并将SQL脚本内容传入执行。这样可以处理不同分隔符的SQL文件。
摘要由CSDN通过智能技术生成

bd96500e110b49cbb3cd949968f18be7.png

I have a sql script file, i need to execute commands present in that through java. I searched in internet regarding the same, i got some code defining parsers to split the SQL statements and executing that. But none of them worked for my sql script file.Because my script file contains both create statements and alter statements without semicolon at the end[Instead it has GO]Can anybody suggest a solution to execute the script file?

Thanks,

Mahesh

解决方案

For simple scripts I generally use this class from ibatis - ScriptRunner. Alternative you can spawn a new db client process from Java and feed in the script you wan't execute. This will work for all scripts, as simple solutions like ScriptRunner don't work well when the delimiters in the sql files get changed for instance.

Here's an example how to feed the sql as a string to a spawed db client process:

private void runSql(String pSql) {

String tCommand = "mysql -u " + username + (password != null ? " -p" + password : "") + " " + dbName;

System.out.println(tCommand);

try {

Process tProcess = Runtime.getRuntime().exec(tCommand);

OutputStream tOutputStream = tProcess.getOutputStream();

Writer w = new OutputStreamWriter(tOutputStream);

System.out.println(pSql);

w.write(pSql);

w.flush();

Scanner in = new Scanner(tProcess.getErrorStream());

String errorMessage = "";

while (in.hasNext()) {

errorMessage += in.next() + " ";

}

if (errorMessage.length() > 0) {

System.out.println(errorMessage);

throw new ClientSqlExecutionException(errorMessage);

}

} catch (IOException e) {

e.printStackTrace();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值