从Java创建MySQL数据库

cb0*_*cb0 25 java mysql database

是否可以从Java创建MySQL数据库?

我只看到了这样的连接URL示例,其中在URL中指定了数据库名称:

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

Connection con = DriverManager.getConnection( url, "cb0", "xxx" );
Run Code Online (Sandbox Code Playgroud)

当我只有登录名和密码时,如何创建MySQL数据库?

Jer*_*ley 47

jdbc连接中不需要数据库,因此您可以执行http://forums.mysql.com/read.php?39,99321,102211#msg-102211http://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");
Run Code Online (Sandbox Code Playgroud)


小智 7

要通过Java代码创建数据库,必须使用executeUpdate(sql)而不是以root身份executeQuery(sql);连接到mysql数据库:

connection =  DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull",
    "root", "root"
);
Statement st = connection.createStatement();
st.executeUpdate(sql);
st.close();
Run Code Online (Sandbox Code Playgroud)