是否可以从Java创建MySQL数据库?
我只看过这样的连接URL示例,其中在URL中指定了数据库名称:
String url="jdbc:mysql://localhost:3306/test";
Connection con = DriverManager.getConnection( url,"cb0","xxx" );
当我只有登录名和密码时,如何创建MySQL数据库?
jdbc连接中不需要数据库,因此您可以执行以下建议的操作:http://forums.mysql.com/read.php?39,99321,102211#msg-102211和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");
要通过Java代码创建数据库,必须使用executeUpdate(sql)而不是executeQuery(sql);并以root用户身份连接到mysql数据库:
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull",
"root","root"
);
Statement st = connection.createStatement();
st.executeUpdate(sql);
st.close();
解决此类问题的一种优雅方法是使用Apache的DDL Utils。 它不仅具有允许执行(外部可配置)DDL的基本目的,而且还使应用程序数据库独立。
您可以使用以下行:
try {
String databaseName ="dbName";
String userName ="root";
String password ="yourPassword";
String url ="jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull";
Connection connection = DriverManager.getConnection(url,username, password);
String sql ="CREATE DATABASE" + databaseName;
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
statement.close();
JOptionPane.showMessageDialog(null, databaseName +" Database has been created successfully","System Message", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
}
请给我您的电子邮件地址,以便我可以发送JAR文件。
谢谢。 但请注意,这个问题是6年前:)
为了使事情变得更加简单,您可以使用NetBeans 6.5,它使设置SQL数据库变得非常容易。 我现在正在使用它们,并且可以节省GUI布局和数据库连接。 这是一些有关如何从NetBeans连接到mysql数据库的代码:
//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);
}
}
NetBeans Wiki拥有您在项目中建立sql表所需的所有信息!