能否使用Java创建MySQL数据库?
我只看到过像这样的连接URL示例,其中数据库名称在URL中指定:
String url="jdbc:mysql://localhost:3306/test";
Connection con = DriverManager.getConnection( url, "cb0", "xxx" );
如果只有登录名和密码,我该如何创建MySQL数据库?
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();
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();
}
//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);
}
}