11

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.

K Spriggs
  • 323
  • 3
  • 4
  • 13

8 Answers8

17

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();
    }
}
Zaknafein
  • 398
  • 1
  • 3
  • 16
14

You could always run

int myResult = statement.executeUpdate("CREATE DATABASE IF NOT EXISTS TIGER;")

If this is ran on project start up it will simply check if the database exists and if it doesn't it will create the new database.

For reference: http://dev.mysql.com/doc/refman/5.0/en/create-database.html

lpdavis13
  • 228
  • 2
  • 10
6

Try with this code.

public class DbStuff {

    private static String jdbcDriver = "com.mysql.jdbc.Driver";
    private static String dbName = "TIGER";


    public static void main(String[] args) throws Exception {
        Class.forName(jdbcDriver);
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=");
        Statement s = conn.createStatement();
        int Result = s.executeUpdate("CREATE DATABASE "+dbName);
    }
}
Masudul
  • 21,823
  • 5
  • 43
  • 58
1

First of all,

I would like to thank all those who answered it was very helpful indeed to get different views and opinions.

Here is the solution that I have together.

    public class DbStuff {
    private String jdbcDriver = "com.mysql.jdbc.Driver";
    private String dbAddress = "jdbc:mysql://localhost:3306/";
    private String userPass = "?user=root&password=";
    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) {
            e.printStackTrace();
        } 
        catch (SQLException e) {
            createDatabase();
        }
    }

    private void createDatabase() {
        try {
        Class.forName(jdbcDriver);
        con = DriverManager.getConnection(dbAddress + userPass);
        Statement s = con.createStatement();
        int myResult = s.executeUpdate("CREATE DATABASE " + dbName);
        } 
        catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }

Feel free to comment on any of the code. I know using the e.printStackTrace() is not the best way forward, don't worry It will be modified later on.

K Spriggs
  • 323
  • 3
  • 4
  • 13
1

The easy approach to problem is :

package Database;
import java.sql.*;

public class Database {

 public static void main(String[] args) {
    final  String URl = "JDBC:mysql:/localhost:3306/info";
    final  String id = "root";
    final  String  password = "";

    try
    {
        Connection con1 = DriverManager.getConnection(URl,id,password);
        Statement s1 = con1.createStatement();
        String s = "CREATE DATABASE CLASSIFIED";
        s1.executeUpdate(s);

    }
    catch(SQLException err)
    {
        System.out.println(err.getMessage());
    }

 }

}
olibiaz
  • 2,551
  • 4
  • 29
  • 31
0

On an unrelated (to the question) note:

I don't think it’s ever a good idea to programmatically generate the database. You will be better off using the utility tool that comes with your database. Everyone that works with MySQL will almost certainly be familiar with the utility tool and will not have to become familiar with your Java code, change it, compile it, and run it to make a change. Also, the utility has a rich set of features that your Java code probably doesn't have such as assigning permissions, indexing, setting up foreign keys, etc.

user2810910
  • 279
  • 1
  • 2
0

Few points to note and correct-

  1. You have declared Connection Object as private Connection con; but you are using it as statement = Conn.createStatement();
  2. You have declared a reference to Prepared Statement private PreparedStatement statement; but you are creating instance of Statement statement = Conn.createStatement();. Your code should be -

    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
        Statement  statement = con.createStatement();
        int myResult = statement.executeUpdate("CREATE DATABASE IF NOT EXISTS TIGER"); //should get 0
    }
    catch (SQLException e) {
        System.out.println("Database creation failed");
        e.printStackTrace();
    } 
    

Note that when the return value for executeUpdate is 0, it can mean one of two things:

  • The statement executed was an update statement that affected zero rows.

  • The statement executed was a DDL statement.

Documentation

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

I know this is a bit old. I think the solution of Zaknafein is the best. I just wanted to add, for newbies, if you are having one String for everything to add an & before user.

akallali
  • 29
  • 5