mysql run sql files_SQL脚本文件执行器

package com.ge.digital.spo.sql.execute.ant;

import java.io.File;

import org.apache.tools.ant.Project;

import org.apache.tools.ant.taskdefs.SQLExec;

import org.apache.tools.ant.types.EnumeratedAttribute;

public class AntSqlRunner {

public void runSqlScript() {

String driverClass= "com.mysql.jdbc.Driver";

String url= "jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8";

String username= "root";

String password= "mysql";String targetSqlFolder= "/home/ca6417/upload/RecoverySQL/"; // 存放SQL脚本的目录

String logOutputFolder= "/home/ca6417/upload/RecoverySQL/"; // 执行结果输出目录,出错的时候才会生成错误报告

runSqlScriptFiles(driverClass, url, username, password, targetSqlFolder, logOutputFolder);

}public static void runSqlScriptFiles(String driverClass, String url, String username, String password, String targetSqlFolder,

String logOutputFolder) {

SQLExec sqlExec=new SQLExec();

sqlExec.setDriver(driverClass);

sqlExec.setUrl(url);

sqlExec.setUserid(username);

sqlExec.setPassword(password);// 如果执行过程有语句出错时如何处理,可以选择继续执行或停止.

sqlExec.setOnerror((SQLExec.OnError) (EnumeratedAttribute.getInstance(SQLExec.OnError.class,"stop")));

sqlExec.setPrint(true);

sqlExec.setProject(new Project());

String targetSqlFile=targetSqlFolder;if(!new File(targetSqlFolder).isDirectory()) {

targetSqlFolder=new File(targetSqlFolder).getParentFile().getAbsolutePath();

}

runSqlScript(sqlExec, targetSqlFile, targetSqlFolder, logOutputFolder);

}

private static void runSqlScript(SQLExec sqlExec, String targetFile, String targetSqlFolder, String logOutputFolder) {

File file=new File(targetFile);if(file.isDirectory()) {

// 如果是目录,遍历执行所有脚本for(File f :file.listFiles()) {

String fileStr=f.getAbsolutePath();

runSqlScript(sqlExec, fileStr, file.getAbsolutePath(), logOutputFolder);

}

}else{

// 如果是脚本文件,执行SQL脚本

String targetSqlFile=targetFile;

String logOutputFile=getLogOutputFile(logOutputFolder, targetSqlFolder, targetSqlFile);

runSqlScriptFile(sqlExec, targetSqlFile, logOutputFile);

}

}

private static void runSqlScriptFile(SQLExec sqlExec, String targetSqlFile, String logOutputFile) {

sqlExec.setSrc(new File(targetSqlFile));

sqlExec.setOutput(new File(logOutputFile));

sqlExec.execute();

System.out.println(targetSqlFile+ "execute success.");

}

private static String getLogOutputFile(String logOutputFolder, String targetSqlFolder, String targetSqlFile) {

String logFileName= targetSqlFile.substring(0, targetSqlFile.indexOf(".")) + ".txt";

logFileName=logFileName.replace(targetSqlFolder, logOutputFolder);returnlogFileName;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值