如何使用 JDBC API 將主鍵約束新增到資料庫表列?


你可以使用 ALTER TABLE 命令將主鍵約束新增到表的列。

語法

ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);

我們假定資料庫中有一個名為 Dispatches 的表,其中有 7 列,分別是 id、CustomerName、DispatchDate、DeliveryTime、Price 和 Location,描述如下所示

+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  |     | NULL    |       |
| CustomerName | varchar(255) | YES  |     | NULL    |       |
| DispatchDate | date         | YES  |     | NULL    |       |
| DeliveryTime | time         | YES  |     | NULL    |       |
| Price        | int(11)      | YES  |     | NULL    |       |
| Location     | text         | YES  |     | NULL    |       |
| ID           | int(11)      | NO   |     | NULL    |       |
+--------------+--------------+------+-----+---------+-------+

以下 JDBC 程式與 MySQL 資料庫建立連線,並將主鍵約束新增到名為 id 的列。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Adding_PrimaryKey_Constraint {
   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:///mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to alter the table
      String query = "ALTER TABLE Sales ADD CONSTRAINT MyPrimaryKey PRIMARY KEY(ID)";
      //Executing the query
      stmt.executeUpdate(query);
      System.out.println("Constraint added......");
   }
}

輸出

Connection established......
Constraint added......

由於我們在名為 id 的列上添加了主鍵約束,因此如果你使用描述命令獲取 Sales 表的描述,你可以觀察到 Key 值 PRI 新增到 Id 的後面。

mysql> describe sales;
+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  |     | NULL    |       |
| CustomerName | varchar(255) | YES  |     | NULL    |       |
| DispatchDate | date         | YES  |     | NULL    |       |
| DeliveryTime | time         | YES  |     | NULL    |       |
| Price        | int(11)      | YES  |     | NULL    |       |
| Location     | text         | YES  |     | NULL    |       |
| ID           | int(11)      | NO   | PRI | NULL    |       |
+--------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)

更新日期:30-Jul-2019

649 次瀏覽

開啟你的 事業

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.