天天看點

java sql 工具類_Java執行Sql腳本工具類

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);

}

}

}