如何使用 JDBC API 為資料庫中表的某列新增唯一鍵約束?


你可以使用 ALTER TABLE 命令為某列新增唯一約束

語法

ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);

假設我們有一個名為 Dispatches 的表在資料庫中,有 7 列,即 id、CustomerName、DispatchDate、DeliveryTime、Price 和 Location,如下所示

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

以下 JDBC 程式建立與 MySQL 資料庫的連線,併為名為 CustomerName 的列新增一個 UNIQUE 約束。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class UniqueKey_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 MyUniqueConstraint UNIQUE(ProductName)";
      //Executing the query
      stmt.executeUpdate(query);
      System.out.println("Constraint added......");
   }
}

輸出

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

由於我們對名為 ProductName 的列添加了 UNIQUE 約束,如果你使用 describe 命令獲取 Sales 表的描述,你可能會看到 Key 值 UNI 新增到了 ProductName 對面。

mysql> describe sales;
+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  | UNI | NULL    |       |
| CustomerName | varchar(255) | NO   |     | 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)

更新時間: 2019 年 7 月 30 日

499 次瀏覽

開啟你的職業

完成課程以獲取認證

開始
廣告
© . All rights reserved.