java通過ScriptRunner執行存儲過程sql腳本
執行存儲過程時需要自定義結束分隔符,定義腳本中的語句一次完整的執行;
主要代碼:
@Component
public class InitializableDatabaseRunner implements CommandLineRunner {
@Autowired
private DataSourceProperties dataSourceProperties;
@Override
public void run(String... args) throws Exception {
try {
Connection conn =getConnection();
ScriptRunner scriptRunner = new ScriptRunner(conn);
Resources.setCharset(Charset.forName("UTF-8")); //設置字符集,不然中文亂碼插入錯誤
scriptRunner.setEscapeProcessing(false);
scriptRunner.setRemoveCRs(true);
scriptRunner.setSendFullScript(false);
scriptRunner.setAutoCommit(true);
//分隔符,還未驗證具體功能
scriptRunner.setFullLineDelimiter(false);
//每條命令間的分隔符
scriptRunner.setDelimiter("$$");
// 從class目錄下直接讀取
List<String> files = getFiles("F:\\resetsql\\");
for (String file : files) {
InputStream inputStream = new FileInputStream(new File(file));
Reader reader = new InputStreamReader(inputStream,"utf-8");
scriptRunner.runScript(reader);
}
scriptRunner.closeConnection();
conn.close();
System.out.println("sql腳本執行完畢");
} catch (Exception e) {
System.out.println("sql腳本執行發生異常");
e.printStackTrace();
}
}
/**
* @Author:
* @Description:獲取某個目錄下所有直接下級文件,不包括目錄下的子目錄的下的文件,所以不用遞歸獲取
* @Date:
*/
public List<String> getFiles(String path) {
List<String> files = new ArrayList<String>();
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
files.add(tempList[i].toString());
//文件名,不包含路徑
//String fileName = tempList[i].getName();
}
}
return files;
}
private Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName(dataSourceProperties.getDriverClassName());
return DriverManager.getConnection(dataSourceProperties.getUrl(),dataSourceProperties.getUsername(),dataSourceProperties.getPassword());
}
}
腳本示例:
DROP PROCEDURE IF EXISTS Showjob;$$ CREATE PROCEDURE Showjob() BEGIN SELECT * FROM sys_job; END;$$