使用JDBC不仅能连接操作数据库,甚至还能创建数据库,只需要权限允许的条件下,比如root。
public class DBCreateTest {
public static String CONN_URL = "jdbc:mysql://localhost:3306";
public static Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DBCreateTest.CONN_URL, "root", "123456");
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
String sql = "CREATE DATABASE if not exists `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;";
try {
Statement stmt = DBCreateTest.getConn().createStatement();
stmt.executeUpdate(sql);
stmt.close();
System.out.println("successed!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}