spring boot 執行sql檔案
現有個需求需要動態連線到不同資料庫,執行sql檔案,類似於navicat這種,可以執行sql
1.匯入依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
2.在啟動類中加入
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
防止spring 專案啟動的時候自動注入資料庫連線資訊(如果專案中有依賴資料庫跳過該步驟)
3.
package cn.ucmed.licensemanager.client.utils;
import java.io.*;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import cn.ucmed.licensemanager.client.model.ExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
/**
* @Author: li
* @Date: 2020/11/5/005 19:58
* @describe sql
*/
@Slf4j
public class SqlExecutor {
public static ExecuteResult executeSql(String taskStepId, String url, String userName, String userPassword, String sql) {
ExecuteResult executeResult = new ExecuteResult();
executeResult.setTaskStepId(taskStepId);
//sql執行輸出流
StringWriter succeedWriter = new StringWriter();
PrintWriter succeedOut = new PrintWriter(succeedWriter);
StringWriter errorWriter = new StringWriter();
PrintWriter errorOut = new PrintWriter(errorWriter);
Connection conn = null;
ScriptRunner runner;
try {
conn = getMySqlConnection(url, userName, userPassword);
} catch (Exception e) {
executeResult.setStatus("資料庫連線錯誤");
executeResult.setLog(e.getStackTrace().toString());
try {
conn.close();
} catch (Exception ee) {
log.error(url + "關閉連線錯誤!");
}
return executeResult;
}
runner = new ScriptRunner(conn);
//設定字符集,不然中文亂碼插入錯誤
Resources.setCharset(Charset.forName("UTF-8"));
runner.setAutoCommit(false);
runner.setSendFullScript(true);
//設定日誌
runner.setLogWriter(succeedOut);
runner.setErrorLogWriter(errorOut);
//遇到錯誤停止
runner.setStopOnError(true);
// 絕對路徑讀取
// Reader read = new FileReader(new File("C:\\Users\\Ucmed\\Documents\\1.sql"));
// 從class目錄下直接讀取
// Reader read = Resources.getResourceAsReader("test.sql");
Reader read = new StringReader(sql);
try {
runner.runScript(read);
} catch (Exception e) {
executeResult.setStatus("sql指令碼執行發生異常");
executeResult.setLog(errorWriter.toString());
return executeResult;
} finally {
try {
runner.closeConnection();
conn.close();
} catch (Exception e) {
log.error(url + "關閉連線錯誤!");
}
}
executeResult.setSucceed(true);
executeResult.setLog(succeedWriter.toString());
executeResult.setStatus("執行成功");
return executeResult;
}
/**
* @return
* @throws Exception
* @功能描述: 獲取資料庫連線
*/
public static Connection getMySqlConnection(String url, String userName, String userPassword) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(url, userName, userPassword);
}
public static void main(String[] args) {
ExecuteResult executeResult = SqlExecutor.executeSql("123", "jdbc:mysql://192.168.2.42:30306/manager?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai", "root", "123456", "select * from project;");
System.out.println(executeResult);
}
}
package cn.ucmed.licensemanager.client.model;
/**
* @Author: li
* @Date: 2020/12/11/011 13:48
* @describe 介面返回封裝類
*/
public class ExecuteResult {
private String taskStepId;
private boolean isSucceed = false;
private String status;
private String logs;
public String getTaskStepId() {
return taskStepId;
}
public void setTaskStepId(String taskStepId) {
this.taskStepId = taskStepId;
}
public boolean isSucceed() {
return isSucceed;
}
public void setSucceed(boolean succeed) {
isSucceed = succeed;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLog() {
return logs;
}
public void setLog(String log) {
this.logs = log;
}
@Override
public String toString() {
return "ExecuteResult{" +
"taskStepId='" + taskStepId + '\'' +
", isSucceed=" + isSucceed +
", status='" + status + '\'' +
", logs='" + logs + '\'' +
'}';
}
}
相關文章
- 如何執行Spring Boot專案Spring Boot
- sqlplus執行sql檔案報錯SQL
- python3執行.sql檔案PythonSQL
- Spring Boot 配置檔案Spring Boot
- 上傳執行sql檔案到linuxSQLLinux
- CMD 執行大檔案SQL指令碼SQL指令碼
- 用PostgreSQL執行檔案中的SQL程式SQL
- Spring Boot執行緒安全指南Spring Boot執行緒
- Spring Boot的檔案上傳Spring Boot
- spring boot配置檔案相關Spring Boot
- Spring Boot 配置檔案總結Spring Boot
- Spring Boot 分片上傳檔案Spring Boot
- Spring Boot 整合阿里雲 OSS 進行檔案儲存Spring Boot阿里
- maven外掛執行過程中自動執行sql檔案MavenSQL
- mysql一次執行多個SQL檔案MySql
- Docker中Mysql容器內如何執行SQL檔案?DockerMySql
- Hazelcast JET在Spring Boot上執行ASTSpring Boot
- Spring Boot中用@RequestMapping 提供 Zip 檔案Spring BootAPP
- Spring Boot的配置檔案管理技巧Spring Boot
- Spring boot + Vue axios 檔案下載Spring BootVueiOS
- Spring Boot @PropertySource 載入指定配置檔案、@ImportResource 匯入Spring 配置檔案Spring BootImport
- [maven][spring boot] mvn spring-boot:run啟動時,指定pom檔案MavenSpring Boot
- .Oracle固定執行計劃之SQL PROFILE概要檔案OracleSQL
- Spring Boot入門(一):使用IDEA建立Spring Boot專案並使用yaml配置檔案Spring BootIdeaYAML
- spring-boot-admin對spring-boot專案進行監控Springboot
- Spring Boot @Async 非同步任務執行Spring Boot非同步
- Spring Boot 檔案上傳與下載Spring Boot
- Spring boot 獲取yml檔案工具類Spring Boot
- spring cloud+spring boot 電子商務spring boot獲取配置檔案的屬性CloudSpring Boot
- spring boot itextPdf根據模板生成pdf檔案Spring Boot
- 使用Spring Boot實現檔案上傳功能Spring Boot
- 精進 Spring Boot 03:Spring Boot 的配置檔案和配置管理,以及用三種方式讀取配置檔案Spring Boot
- Windows環境下實現批量執行Sql檔案勒鴛WindowsSQL
- Laravel 使用 sql 語句 和 sql 檔案 來建立執行資料庫遷移LaravelSQL資料庫
- spring boot 專案報錯找不到compose.yaml檔案Spring BootYAML
- Spring 對檔案上傳下載的支援(Spring boot實現)Spring Boot
- 在Spring Boot程式中上傳和下載檔案Spring Boot
- Spring boot 讀取properties檔案的四種方式Spring Boot