public class RunSqlScript {
private static volatile RunSqlScript instance;
private String url;
private String username;
private String password;
private Connection conn;
private ScriptRunner runner;
private boolean isTest = false;
private RunSqlScript(String url, String username, String password) {
this.url = url;
this.username = username;
this.password = password;
}
public static RunSqlScript build(String url, String username, String password) {
if (instance == null) {
synchronized (RunSqlScript.class) {
if (instance == null) {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
instance = new RunSqlScript(url, username, password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
return instance;
}
public boolean testConn() {
try {
if (conn != null) {
close();
}
conn = DriverManager.getConnection(url, username, password);
runner = new ScriptRunner(conn);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
isTest = true;
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void run(Queue sqls) {
if (!isTest) {
throw new RuntimeException("还没有执行测试方法,请先执行测试方法");
}
try {
// 获取数据库相关配置信息
while (!sqls.isEmpty()) {
String sqlPath = sqls.poll();
if (!StringUtil.isEmpty(sqlPath)) {
runner.runScript(new FileReader(sqlPath));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void reSetDataSource(String url, String username, String password) {
if (StringUtil.isEmpty(url) || StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
throw new RuntimeException("数据库连接地址Url|用户名|密码都不能为空");
}
isTest = false;
this.url = url;
this.password = password;
this.username = username;
testConn();
}
public void close() {
if (conn == null) {
return;
}
try {
conn.close();
isTest = false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}