您可以使用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();
      //查询更改表
      String query = "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)