views:

916

answers:

4

Is there any possability to create a database within mysql from java.

I'm only aware of the

String url="jdbc:mysql://localhost:3306/test";

Connection con = DriverManager.getConnection( url, "cb0", "xxx" );

syntax but here you have to specify a database name in the 'url'.

But how do I create a mysql database when I only have a login name and password, but no knowledge about the existing databases ?

+1  A: 

Make default database to mysql. Next, create database you need and make it default using command USE

abatishchev
+10  A: 

The database isn't required in the jdbc connection, so you can do something like recommended at http://forums.mysql.com/read.php?39,99321,102211#msg-102211 and http://marc.info/?l=mysql-java&m=104508605511590&w=2:

Conn = DriverManager.getConnection
("jdbc:mysql://localhost/?user=root&password=rootpassword"); 
s=Conn.createStatement();
int Result=s.executeUpdate("CREATE DATABASE databasename");
Jeremy Stanley
+1  A: 

To make things even easier, you can use NetBeans 6.5 and it makes setting up SQL databases SO much easier. I'm using them right now and its a lifesaver on GUI layouts and database connections. Here's some code on how I connect to my sql database from NetBeans:

//these are variables i declare in the beginning of my code
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String DATABASE_URL = "jdbc:mysql://localhost:3306/jtschema";
private Connection connection = null;
public static Statement statement = null;


public void initSQLServer() {
try {
    Class.forName(DRIVER).newInstance();
    try {
        connection = DriverManager.getConnection(DATABASE_URL, "root", "Dropatrain!248");
        statement = connection.createStatement();
    } catch (SQLException e) {
        System.out.println("SQLException: " + e.getMessage());
        System.out.println("SQLState: " + e.getSQLState());
        System.out.println("VendorError: " + e.getErrorCode());
    }
} catch (Exception ex) {
    System.out.println(ex);
}

}

durrellp
NetBeans wiki has all the info you need tho set up a sql table in your project also!
durrellp
+1  A: 

An elegant approach to such issues is using DDL Utils from Apache. Not only would it serve the basic purpose of allowing to execute your (externally configurable) DDLs, but also would make your application database independent.

pugmarx