如何使用 JDBC API 在 MySQL 中建立資料庫?


A. 通常,您可以使用 CREATE DATABASE 查詢建立資料庫。

語法

CREATE DATABASE DatabaseName;

要使用 JDBC API 建立資料庫,您需要

  • 註冊驅動程式:使用 DriverManager 類的 registerDriver() 方法註冊驅動程式類。將驅動程式類名作為引數傳遞給它。

  • 建立連線:使用 DriverManager 類的 getConnection() 方法連線到資料庫。將 URL(字串)、使用者名稱(字串)、密碼(字串)作為引數傳遞給它。

  • 建立語句:使用 Connection 介面的 createStatement() 方法建立一個 Statement 物件。

  • 執行查詢:使用 Statement 介面的 execute() 方法執行查詢。

示例

以下 JDBC 程式建立與 MySQL 的連線並建立一個名為 mydatabase 的資料庫

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateDatabaseExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql:///";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to create a database
      String query = "CREATE database MyDatabase";
      //Executing the query
      stmt.execute(query);
      System.out.println("Database created");
   }
}

輸出

Connection established......
Database created......

show databases 命令為您提供 MySQL 中資料庫的列表。如果您使用此命令驗證資料庫列表,則可以看到新建立的資料庫為

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| base               |
| details            |
| exampledatabase    |
| logging            |
| mydatabase         |
| mydb               |
| mysql              |
| performance_schema |
| students           |
| sys                |
| world              |
+--------------------+
12 rows in set (0.00 sec)

更新於: 2019年7月30日

2K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.