Create MySQL database from Java
Is it possible to create a MySQL database from Java?
I have only seen connection URLs examples like this where the database name is specified in the URL:
String url="jdbc:mysql://localhost:3306/test";
Connection con = DriverManager.getConnection( url, "cb0", "xxx" );
How can I create a MySQL database when I only have a login name and password?
Solution 1:
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");
Solution 2:
To create database through Java code, you must use executeUpdate(sql)
instead of executeQuery(sql);
and connect to the mysql
database as root:
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull",
"root", "root"
);
Statement st = connection.createStatement();
st.executeUpdate(sql);
st.close();
Solution 3:
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.