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

更新於:2020年6月29日

3K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.