如何使用 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://127.0.0.1/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)
广告