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