美文网首页
springboot 启动时创建数据库

springboot 启动时创建数据库

作者: 爱工作的java程序猿 | 来源:发表于2020-11-17 13:42 被阅读0次
    
    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`;");
            }
        }
    }
    
    
    

    相关文章

      网友评论

          本文标题:springboot 启动时创建数据库

          本文链接:https://www.haomeiwen.com/subject/ttuxiktx.html