K Spriggs K Spriggs - 1 year ago 55
SQL Question

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 {
con = DriverManager.getConnection(dbAddress + dbName, userName, password);

catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
catch (SQLException e) {
// TODO Auto-generated catch block

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.

Answer Source

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 {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=");
        Statement s = conn.createStatement();
        int Result = s.executeUpdate("CREATE DATABASE "+dbName);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download