import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* springboot 啟動(dòng)創(chuàng)建數(shù)據(jù)庫(kù)
* @author liujiasheng
*/
@Configuration
@Slf4j
public class StartupCreateDatabase {
@Resource
private HikariDataSource dataSource;
@PostConstruct
public void init() throws ClassNotFoundException, URISyntaxException, SQLException {
// 通過(guò) hikari 獲取數(shù)據(jù)庫(kù)連接信息
String driver = dataSource.getDriverClassName();
String url = dataSource.getJdbcUrl();
String username = dataSource.getUsername();
String password = dataSource.getPassword();
Class.forName(driver);
URI uri = new URI(url.replace("jdbc:", ""));
String host = uri.getHost();
int port = uri.getPort();
String path = uri.getPath();
String connectUrl = "jdbc:mysql://" + host + ":" + port;
try (Connection connection = DriverManager.getConnection(connectUrl, username, password);
Statement statement = connection.createStatement()) {
// 創(chuàng)建數(shù)據(jù)庫(kù)
statement.executeUpdate("CREATE DATABASE IF NOT EXISTS `" + path.replace("/", "") + "` DEFAULT CHARACTER SET = `utf8` COLLATE `utf8_general_ci`;");
}
}
}
springboot 啟動(dòng)時(shí)創(chuàng)建數(shù)據(jù)庫(kù)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 工具:eclipse需求:客戶電腦上已經(jīng)安裝了mysql(建議用戶名root 密碼1234--不然要改密碼),現(xiàn)在...
- 如何在SpringBoot2啟動(dòng)時(shí)自動(dòng)創(chuàng)建表、插入數(shù)據(jù) 一、springboot2中如何根據(jù)實(shí)體類自動(dòng)生成表 只需...
- 1. 添加maven依賴(基于SpringBoot 2.1.1.RELEASE版本) 2.操作 功能介紹:當(dāng)項(xiàng)目啟...
- 1. 前言 Docker在開(kāi)發(fā)中使用的越來(lái)越多了,最近搞了一個(gè)Spring Boot應(yīng)用,為了方便部署將Mysql...
- 第一步創(chuàng)建springboot項(xiàng)目,jpa,mysql,代碼如下:application.yml 實(shí)體類 運(yùn)行sp...