如何使用 JDBC API 更改現有表中列的資料型別?


您可以使用 ALTER TABLE 命令更改表中列的資料型別。

語法

ALTER TABLE Sales MODIFY COLUMN column_name column_new_datatuype

假設我們在資料庫中有一個名為 Sales 的表,其中包含 7 列,分別是 ProductName、CustomerName、DispatchDate、DeliveryTime、Price、Location 和 ID,其描述如下:

+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  |     | NULL    |       |
| CustomerName | varchar(255) | YES  |     | NULL    |       |
| DispatchDate | date         | YES  |     | NULL    |       |
| DeliveryTime | time         | YES  |     | NULL    |       |
| Price        | int(11)      | YES  |     | NULL    |       |
| Location     | varchar(255) | YES  |     | NULL    |       |
| ID           | int(11) | NO |      | NULL|         |       |
+--------------+--------------+------+-----+---------+-------+

以下 JDBC 程式建立與 MySQL 資料庫的連線,並將列 location 的資料型別從 varchar 更改為 text。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ChangingDatatype {
   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 MODIFY COLUMN Location Text";
      //Executing the query
      stmt.executeUpdate(query);
      System.out.println("Column datatype changed......");
   }
}

輸出

Connection established......
Column datatype changed......

由於我們更改了 location 列的型別,如果您使用 describe 命令獲取 Sales 表的描述,您可以觀察到名為 location 的列的資料型別已從 varchar 更改為 text。

mysql> describe sales;
+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  |     | 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   |     | NULL    |       |
+--------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)

更新於: 2019年7月30日

764 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.