springboot 启动时创建数据库
2020-11-17 本文已影响0人
爱工作的java程序猿
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 启动创建数据库
* @author liujiasheng
*/
@Configuration
@Slf4j
public class StartupCreateDatabase {
@Resource
private HikariDataSource dataSource;
@PostConstruct
public void init() throws ClassNotFoundException, URISyntaxException, SQLException {
// 通过 hikari 获取数据库连接信息
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()) {
// 创建数据库
statement.executeUpdate("CREATE DATABASE IF NOT EXISTS `" + path.replace("/", "") + "` DEFAULT CHARACTER SET = `utf8` COLLATE `utf8_general_ci`;");
}
}
}