如何使用 JDBC API 删除数据库中表列上的约束?

jdbcjava 8object oriented programmingprogramming更新于 2025/4/30 21:37:17

您可以使用 ALTER TABLE 命令删除表列上的约束。

语法

ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;

假设数据库中有一个名为 Dispatches 的表,该表有 7 列,即 id、CustomerName、DispatchDate、DeliveryTime、Price 和 Location,其描述如下所示:

+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  | UNI | 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 数据库建立连接,并从 Sales 表中删除名为 MyUniqueConstraint 的约束。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DroppingConstraint {
   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("连接已建立......");
      //创建语句
      Statement stmt = con.createStatement();
      //查询以更改表
      String query = "ALTER TABLE Sales DROP INDEX MyUniqueConstraint";
      //执行查询
      stmt.executeUpdate(query);
      System.out.println("Constraint dropped......");
   }
}

输出

Connection established......
Constraint dropped......

由于我们从销售表中删除了名为 MyUniqueConstraint 的唯一约束(位于 ProductName 列上),如果您使用 describe 命令获取销售表的描述,您可以观察到与 ProductName 相反添加的键值 UNI 已被删除。

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)

相关文章