从Java创建MySQL数据库

是否可以从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的基本目的,还可以使您的应用程序数据库独立。

为了使事情变得更加简单,您可以使用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); } } 

你可以使用这一行:

  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(); }