/**
* cn.esoon.util
*
* @author surpass
* @date 2020/3/3
*/
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;
}
/**
* 创建脚本执行对象
*
* @param url 数据库连接地址
* @param username 数据库连接用户名
* @param password 数据库连接密码
* @return
*/
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;
}
/**
* 测试连接是否成功
*
* @return 如果成功返回true, 否则抛异常
*/
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);
}
}
/**
* 运行指定的sql脚本
*
* @param sqls 需要执行的sql脚本的名字
*/
public void run(Queue<String> 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);
}
}
/**
* 重新设置数据源,并测试是否连接成功
*
* @param url
* @param username
* @param password
*/
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);
}
}
}