Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a database in mysql from java

Could you help with this problem.

I'm trying to create and then use a database called TIGER.

I have no problem if I create the database in MySQL and it runs perfectly.

What I would like to do is create it from Java. So that when the code is being run for the first time it creates the database as part of the initial launch. I would like to box it up in a nice clean method if possible.

Could it be possible for someone to show me where you actually position the code

Here is the code

    private String jdbcDriver = "com.mysql.jdbc.Driver";
    private String dbAddress = "jdbc:mysql://localhost:3306/";
    private String dbName = "TIGER";
    private String userName = "root";
    private String password = "";

    private PreparedStatement statement;
    private ResultSet result;
    private Connection con;

    public DbStuff() {
        try {
            Class.forName(jdbcDriver);
            con = DriverManager.getConnection(dbAddress + dbName, userName, password);
        } 

        catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

and here is the code to create the database

    con = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword"); 
    statement = Conn.createStatement();
    int myResult = statement.executeUpdate("CREATE DATABASE TIGER");

Thanks in advance and any and all help is appreciated

Sorry for the mistakes as I'm a long term reader but a new writer.

When I try do run the main part of the code it generates an SQLException because the database doesn't exist. At this point I would like to catch the exception and create the database at that point. But when I try this it doesn't create the database.

like image 602
K Spriggs Avatar asked Sep 25 '13 15:09

K Spriggs


1 Answers

I suggest to use this snippet of code

private String jdbcDriver = "com.mysql.jdbc.Driver";
private String dbAddress = "jdbc:mysql://localhost:3306/TIGER?createDatabaseIfNotExist=true";
private String userName = "root";
private String password = "";

private PreparedStatement statement;
private ResultSet result;
private Connection con;

public DbStuff() {
    try {
        Class.forName(jdbcDriver);
        con = DriverManager.getConnection(dbAddress, userName, password);
    } 

    catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
like image 168
Zaknafein Avatar answered Oct 07 '22 09:10

Zaknafein