如何使用JDBC API将自动增量设置为表中的现有列?
您可以使用ALTERTABLE命令向表中的列添加/设置自动增量约束。
语法
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 { //注册驱动程序 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(); //设置列ID自动递增 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......
如果使用“选择”命令检索“销售”表的内容,则可以看到名为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)