Create Mysql database at runtime

Asked

Viewed 166 times

0

I am developing a Java registration application and I need this application to be executed to check if there is a database, if the database does not exist it creates this database and its tables so that the application can enter the data.

Can someone help me?

1 answer

1

On the basis of the answers How to check if a table exists in Mysql and another in Soen.

// abre a conexão com o banco de dados
Connection conexao = DriverManager.getConnection(URL, USUÁRIO, SENHA);

// acessa os metadados do banco de dados
DatabaseMetaData metadados = conexao.getMetaData();

// erificar se a tabela existe
ResultSet tabela = metadados.getTables(null, null, "MinhaTabela", null);

// condição, caso a tabela exista
if (tabela.next()) {
    // faça algo se a tabela existir
} else {
    // faça algo se a não tabela existir
    criarTabela();
}

Function to create table

private void criarTabela() throws SQLException {
    String sqlCreate = "CREATE TABLE IF NOT EXISTS MinhaTabela"
            + "  (id              INTEGER(10),"
            + "   nome            VARCHAR(80),"
            + "   email           VARCHAR(80))";

    Statement stmt = conexao.createStatement();
    stmt.execute(sqlCreate);
}

Obs due to me being on a totally unprepared computer, no test can be performed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.