如何使用JDBC API為資料庫表中的列新增NOT NULL約束?


您可以使用ALTER TABLE命令為表的列新增非空約束。

語法

ALTER TABLE table_name MODIFY column_name datatype NOT NULL;

假設我們有一個名為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   | PRI | NULL    |       |
+--------------+--------------+------+-----+---------+-------+

下面的JDBC程式建立與MySQL資料庫的連線,併為名為CustomerName的列新增NOT NULL約束。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class NotNull_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 MODIFY CustomerName varchar(255) NOT NULL";
      //Executing the query
      stmt.executeUpdate(query);
      System.out.println("Constraint added......");
   }
}

輸出

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

由於我們在名為id CustomerName的列上添加了NOT NULL約束,如果您使用describe命令獲取Sales表的描述,您可以在CustomerName的NULL列下看到NO值。

mysql> describe sales;
+--------------+--------------+------+-----+---------+-------+
| 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    |       |
+--------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)

更新於:2019年7月30日

354次瀏覽

啟動您的職業生涯

完成課程獲得認證

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