如何使用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数据库的连接,并将NOT NULL约束添加到名为CustomerName的列。

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 {
      //注册驱动程序
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //获得连接
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //创建语句
      Statement stmt = con.createStatement();
      //查询更改表
      String query = "ALTER TABLE Sales MODIFY CustomerName varchar(255) NOT NULL";
      //执行查询
      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)