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


A. 你可以使用CREATE TABLE查詢在資料庫中建立表。

語法

CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);

要使用JDBC API在資料庫中建立表,你需要:

  • 註冊驅動程式:使用**DriverManager**類的**registerDriver()**方法註冊驅動程式類。將驅動程式類名作為引數傳遞。
  • 建立連線:使用**DriverManager**類的**getConnection()**方法連線到資料庫。將URL(字串)、使用者名稱(字串)、密碼(字串)作為引數傳遞。
  • 建立Statement物件:使用**Connection**介面的**createStatement()**方法建立一個Statement物件。
  • 執行查詢:使用Statement介面的execute()方法執行查詢。

示例

下面的JDBC程式建立與MySQL的連線,並在名為**SampleDB**的資料庫中建立一個名為customers的表。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTableExample {
   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:///SampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to create a table
      String query = "CREATE TABLE CUSTOMERS("
         + "ID INT NOT NULL, "
         + "NAME VARCHAR (20) NOT NULL, "
         + "AGE INT NOT NULL, "
         + "SALARY DECIMAL (18, 2), "
         + "ADDRESS CHAR (25) , "
         + "PRIMARY KEY (ID))";
      stmt.execute(query);
      System.out.println("Table Created......");
   }
}

輸出

Connection established......
Table Created......

在MySQL中,show tables命令會顯示當前資料庫中的表列表。

如果你驗證名為sampledb的資料庫中的表列表,你可以在其中看到新建立的表,如下所示:

mysql> show tables;
+--------------------+
| Tables_in_sampledb |
+--------------------+
| articles           |
| customers          |
| dispatches         |
| technologies       |
| tutorial           |
+--------------------+
5 rows in set (0.00 sec)

更新於:2019年7月30日

6000+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告