如何使用 JDBC 获取 PreparedStatement 生成的自动递增值?
创建表时,在某些情况下,我们需要为某些列(例如 ID 列)自动生成/递增值。各种数据库以不同的方式支持此功能。
在 **MySQL** 数据库中,您可以使用以下语法声明自动递增列。
CREATE TABLE table_name( ID INT PRIMARY KEY AUTO_INCREMENT, column_name1 data_type1, column_name2 data_type2, column_name3 data_type3, column_name4 data_type4, ............ ........... );
在向表中插入记录时,无需为自动递增列插入值。这些值将自动生成。
例如,如果表中有一列名为 ID,数据类型为 INT,并且是自动递增的,并且该表中已经有 6 条记录。当您使用 INSERT 语句插入下一条记录时,新记录的 ID 值将为 7,其下一条记录的 ID 值将为 8。
(您可以为这些自动递增列指定初始值和间隔。)
检索自动递增的值
如果您使用 **PreparedStatement** 对象将记录插入到包含自动递增列的表中。
您可以使用 **getGeneratedKeys()** 方法检索当前 PreparedStatement 对象生成的该特定列的值。
示例
让我们在 MySQL 数据库中创建一个名为 **sales** 的表,其中一列为自动递增列,使用如下所示的 CREATE 语句:
CREATE TABLE Sales( ID INT PRIMARY KEY AUTO_INCREMENT, ProductName VARCHAR (20), CustomerName VARCHAR (20), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(20) );
现在,要使用 **PreparedStatement** 对象将记录插入此表,并检索由此生成的自动递增值:
- 使用 DriverManager 类的 **registerDriver()** 方法或名为 Class 的类的 forName() 方法注册所需数据库的驱动程序类。
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
- 通过将数据库的 URL、数据库用户的用户名和密码(以字符串格式)作为参数传递给 DriverManager 类的 **getConnection()** 方法来创建 Connection 对象。
Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password");
- 使用连接接口的 prepareStatement() 方法创建一个 **PreparedStatement** 对象。
将包含绑定变量的 **INSERT** 语句(以字符串格式)作为参数传递给此方法,并将 Statement.RETURN_GENERATED_KEYS 作为另一个参数,如下所示:
//Query to Insert values to the sales table String insertQuery = "INSERT INTO Sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) VALUES (?, ?, ?, ?, ?, ?)"; //Creating a PreparedStatement object PreparedStatement pstmt = con.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
- 使用 **setXXX()** 方法将每条记录的值设置为绑定变量,并将其添加到批处理中。
pstmt.setString(1, "Key-Board"); pstmt.setString(2, "Raja"); pstmt.setDate(3, new Date(1567315800000L)); pstmt.setTime(4, new Time(1567315800000L)); pstmt.setInt(5, 7000); pstmt.setString(6, "Hyderabad"); pstmt.addBatch(); pstmt.setString(1, "Earphones"); pstmt.setString(2, "Roja"); pstmt.setDate(3, new Date(1556688600000L)); pstmt.setTime(4, new Time(1556688600000L)); pstmt.setInt(5, 2000); pstmt.setString(6, "Vishakhapatnam"); pstmt.addBatch(); ........... ...........
将所有记录的值添加到批处理后,使用 executeBatch() 方法执行批处理。
pstmt.executeBatch();
- 最后,使用 **getGeneratedKeys()** 方法获取此 PreparedStatement 对象生成的自动递增键。
ResultSet rs = pstmt.getGeneratedKeys();
while (rs.next()) {
System.out.println(rs.getString(1));
}下面的 JDBC 程序使用 PreparedStatement 将 5 条记录插入到 Sales 表(如上所述创建)中,并检索并显示由此生成的自动递增值。
示例
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
public class RetrievingData_AutoIncrement_Pstmt {
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:///sample_database";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Query to Insert values to the sales table
String insertQuery = "INSERT INTO Sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) VALUES (?, ?, ?, ?, ?, ?)";
//Creating a PreparedStatement object
PreparedStatement pstmt = con.prepareStatement(insertQuery,Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, "Key-Board");
pstmt.setString(2, "Raja");
pstmt.setDate(3, new Date(1567315800000L));
pstmt.setTime(4, new Time(1567315800000L));
pstmt.setInt(5, 7000);
pstmt.setString(6, "Hyderabad");
pstmt.addBatch();
pstmt.setString(1, "Earphones");
pstmt.setString(2, "Roja");
pstmt.setDate(3, new Date(1556688600000L));
pstmt.setTime(4, new Time(1556688600000L));
pstmt.setInt(5, 2000);
pstmt.setString(6, "Vishakhapatnam");
pstmt.addBatch();
pstmt.setString(1, "Mouse");
pstmt.setString(2, "Puja");
pstmt.setDate(3, new Date(1551418199000L));
pstmt.setTime(4, new Time(1551418199000L));
pstmt.setInt(5, 3000);
pstmt.setString(6, "Vijayawada");
pstmt.addBatch();
pstmt.setString(1, "Mobile");
pstmt.setString(2, "Vanaja");
pstmt.setDate(3, new Date(1551415252000L));
pstmt.setTime(4, new Time(1551415252000L));
pstmt.setInt(5, 9000);
pstmt.setString(6, "Chennai");
pstmt.addBatch();
pstmt.setString(1, "Headset");
pstmt.setString(2, "Jalaja");
pstmt.setDate(3, new Date(1554529139000L));
pstmt.setTime(4, new Time(1554529139000L));
pstmt.setInt(5, 6000);
pstmt.setString(6, "Goa");
pstmt.addBatch();
System.out.println("Records inserted......");
//Executing the batch
pstmt.executeBatch();
//Auto-incremented values generated by the current PreparedStatement object
ResultSet res = pstmt.getGeneratedKeys();
System.out.println("Auto-incremented values of the column ID generated by the current PreparedStatement object: ");
while (res.next()) {
System.out.println(res.getString(1));
}
}
}输出
Connection established...... Records inserted...... Auto-incremented values of the column ID generated by the current PreparedStatement object: 1 2 3 4 5
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP