如何使用 JDBC API 为数据库中表的某列添加唯一键约束?
你可以使用 ALTER TABLE 命令为某列添加唯一约束
语法
ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
假设我们有一个名为 Dispatches 的表在数据库中,有 7 列,即 id、CustomerName、DispatchDate、DeliveryTime、Price 和 Location,如下所示
+--------------+--------------+------+-----+---------+-------+ | 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 | | +--------------+--------------+------+-----+---------+-------+
以下 JDBC 程序建立与 MySQL 数据库的连接,并为名为 CustomerName 的列添加一个 UNIQUE 约束。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class UniqueKey_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 ADD CONSTRAINT MyUniqueConstraint UNIQUE(ProductName)";
//Executing the query
stmt.executeUpdate(query);
System.out.println("Constraint added......");
}
}输出
Connection established...... Constraint added......
由于我们对名为 ProductName 的列添加了 UNIQUE 约束,如果你使用 describe 命令获取 Sales 表的描述,你可能会看到 Key 值 UNI 添加到了 ProductName 对面。
mysql> describe sales; +--------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+-------+ | ProductName | varchar(255) | YES | UNI | 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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP