如何使用 JDBC API 向数据库中表的列添加主键约束?

jdbcjava 8object oriented programmingprogramming

您可以使用 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 {
      //注册驱动程序
      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();
      //查询以更改表
      字符串查询 = "ALTER TABLE Sales ADD CONSTRAINT MyPrimaryKey PRIMARY KEY(ID)";
      //执行查询
      stmt.executeUpdate(query);
      System.out.println("Constraint added......");
   }
}

输出

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

由于我们在名为 id 的列上添加了主要约束,如果您使用 describe 命令获取 Sales 表的描述,您可以观察到键值 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)

相关文章