如何使用 JDBC API 将主键约束添加到数据库表列?
你可以使用 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 { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://127.0.0.1/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 MyPrimaryKey PRIMARY KEY(ID)"; //Executing the query stmt.executeUpdate(query); System.out.println("Constraint added......"); } }
输出
Connection established...... Constraint added......
由于我们在名为 id 的列上添加了主键约束,因此如果你使用描述命令获取 Sales 表的描述,你可以观察到 Key 值 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)
广告