如何使用JDBC API刪除資料庫表列上的約束?
您可以使用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 {
//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 DROP INDEX MyUniqueConstraint";
//Executing the query
stmt.executeUpdate(query);
System.out.println("Constraint dropped......");
}
}輸出
Connection established...... Constraint dropped......
由於我們從Sales表中刪除了名為MyUniqueConstraint的唯一約束(該約束位於ProductName列上),如果您使用describe命令獲取Sales表的描述,您可以觀察到ProductName對應的Key值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)
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP