如何使用 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