【问题标题】:How can I create a new schema in mysql from my spring boot app如何从我的 Spring Boot 应用程序在 mysql 中创建新模式
【发布时间】:2018-09-01 16:37:22
【问题描述】:

我想从 Spring Boot 在 mysql 中创建新的数据库模式,因为它是通过命令行完成的 -> create database [schema-name]

我怎样才能做到这一点?

我正在使用休眠,jpa

【问题讨论】:

标签: mysql hibernate jpa spring-boot spring-data


【解决方案1】:

我想你想以编程方式创建数据库。

您可以使用以下代码来完成:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {

    @Value("${database:DEMODB}")
    private String database;

    /**
     * This event is executed as late as conceivably possible to indicate that
     * the application is ready to service requests.
     */
    @Override
    public void onApplicationEvent(final ApplicationReadyEvent event) {

        // Defines the JDBC URL. As you can see, we are not specifying
        // the database name in the URL.
        String url = "jdbc:mysql://localhost";

        // Defines username and password to connect to database server.
        String username = "root";
        String password = "master";

        // SQL command to create a database in MySQL.
        String sql = "CREATE DATABASE IF NOT EXISTS " + database;

        try (Connection conn = DriverManager.getConnection(url, username, password);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

确保该组件将在运行时被组件扫描发现。

您可以使用命令行传递数据库名称,如下所示:

java -jar spring-boot-app.jar --database=test_db

如果没有指定数据库 - 此代码将创建名为 DEMODB 的数据库。 请参阅“数据库”字段上的 @Value 注释。

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 1970-01-01
    • 2016-10-24
    • 2020-07-23
    • 2022-12-06
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    相关资源
    最近更新 更多