如何使用 JDBC API 來設定表中現有列的自動遞增?


可使用 ALTER TABLE 命令向表中的列新增/設定自動遞增約束。

語法

ALTER TABLE table_name ADD id INT PRIMARY KEY AUTO_INCREMENT

假設我們在資料庫中有一張名為 Dispatches 的表,其中有 7 列,即 id、CustomerName、DispatchDate、DeliveryTime、Price 和 Location,描述如下所示

+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  | UNI | 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   | PRI | NULL    |       |
+--------------+--------------+------+-----+---------+-------+

以下 JDBC 程式建立與 MySQL 資料庫的連線,新增一個名為 Id 的列,並將值設定為 id 列,以自動遞增。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class SettingAutoIncrement {
   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();
      //Setting the column id auto-increment
      String query = "ALTER TABLE Sales ADD id INT PRIMARY KEY AUTO_INCREMENT";
      stmt.execute(query);
      stmt.executeBatch();
      System.out.println("Table altered......");
   }
}

輸出

Connection established......
Table altered......

如果你使用 Select 命令檢索 Sales 表的內容,你可以觀察到一個名為 id 的列被新增到表中,其中包含自動遞增的整數值。

mysql> select * from Sales;
+-------------+--------------+--------------+--------------+-------+----------------+----+
| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location       | id |
+-------------+--------------+--------------+--------------+-------+----------------+----+
| Key-Board   | Raja         | 2019-09-01   | 08:51:36     | 7000  | Hyderabad      | 1  |
| Earphones   | Roja         | 2019-05-01   | 05:54:28     | 2000  | Vishakhapatnam | 2  |
| Mouse       | Puja         | 2019-03-01   | 04:26:38     | 3000  | Vijayawada     | 3  |
| Mobile      | Vanaja       | 2019-03-01   | 04:26:35     | 9000  | Vijayawada     | 4  |
| Headset     | Jalaja       | 2019-03-01   | 05:19:16     | 6000  | Vijayawada     | 5  |
+-------------+--------------+--------------+--------------+-------+----------------+----+
5 rows in set (0.00 sec)

更新於: 30-Jul-2019

544 次瀏覽

開啟您的職業生涯

完成課程後獲取認證

開始
廣告
© . All rights reserved.