如何使用 JDBC API 從資料庫中的現有表中刪除列?
你可以使用 ALTER TABLE 命令刪除表中的列。
語法
ALTER TABLE table_name DROP COLUMN column_name;
假設我們有一個名為 Sales 的資料庫表,其中有 7 列,即 id、CustomerName、DispatchDate、DeliveryTime、Price 和 Location,如下所示
+----+-------------+--------------+--------------+--------------+-------+----------------+ | id | productname | CustomerName | DispatchDate | DeliveryTime | Price | Location | +----+-------------+--------------+--------------+--------------+-------+----------------+ | 1 | Key-Board | Raja | 2019-09-01 | 08:51:36 | 7000 | Hyderabad | | 2 | Earphones | Roja | 2019-05-01 | 05:54:28 | 2000 | Vishakhapatnam | | 3 | Mouse | Puja | 2019-03-01 | 04:26:38 | 3000 | Vijayawada | | 4 | Mobile | Vanaja | 2019-03-01 | 04:26:35 | 9000 | Chennai | | 5 | Headset | Jalaja | 2019-04-06 | 05:19:16 | 6000 | Delhi | +----+-------------+--------------+--------------+--------------+-------+----------------+
下面這個 JDBC 程式建立與 MySQL 資料庫的連線,然後從 Sales 表中刪除名為 ID 的列。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DeletingColumn {
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 ID";
//Executing the query
stmt.executeUpdate(query);
System.out.println("Column Deleted......");
}
}輸出
Connection established...... Column Deleted......
由於我們已經刪除了一列,如果你使用 SELECT 命令檢索 Sales 表的內容,你可以只看到 6 列(沒有名為 id 的列),如下所示:
mysql> select * from Sales; +-------------+--------------+--------------+--------------+-------+----------------+ | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location | +-------------+--------------+--------------+--------------+-------+----------------+ | Key-Board | Raja | 2019-09-01 | 05:30:00 | 7000 | Hyderabad | | Earphones | Roja | 2019-05-01 | 05:54:28 | 2000 | Vishakhapatnam | | Mouse | Puja | 2019-03-01 | 04:26:38 | 3000 | Vijayawada | | Mobile | Vanaja | 2019-03-01 | 04:26:35 | 9000 | Chennai | | Headset | Jalaja | 2019-04-06 | 05:19:16 | 6000 | Delhi | +-------------+--------------+--------------+--------------+-------+----------------+ 5 rows in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Java 指令碼
PHP