如何使用 JDBC API 从数据库中的现有表中删除列?
jdbcjava 8object oriented programmingprogramming更新于 2025/5/11 23:08:17
您可以使用 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 {
//注册驱动程序
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 Drop ID";
//执行查询
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)

