如何在JDBC中获取插入ID?

我想在Java中使用JDBC在数据库(在我的情况下是Microsoft SQL Server)中INSERTlogging。 同时,我想获得插入ID。 我怎样才能实现这个使用JDBC API?

如果它是一个自动生成的键,那么你可以使用Statement#getGeneratedKeys()来做到这一点。 您需要在与用于INSERT Statement相同的Statement上调用它。 首先需要使用Statement.RETURN_GENERATED_KEYS创buildStatement.RETURN_GENERATED_KEYS来通知JDBC驱动程序返回密钥。

这是一个基本的例子:

 public void create(User user) throws SQLException { try ( Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS); ) { statement.setString(1, user.getName()); statement.setString(2, user.getPassword()); statement.setString(3, user.getEmail()); // ... int affectedRows = statement.executeUpdate(); if (affectedRows == 0) { throw new SQLException("Creating user failed, no rows affected."); } try (ResultSet generatedKeys = statement.getGeneratedKeys()) { if (generatedKeys.next()) { user.setId(generatedKeys.getLong(1)); } else { throw new SQLException("Creating user failed, no ID obtained."); } } } } 

请注意,您依赖于JDBC驱动程序是否有效。 目前,大多数最新版本都可以,但是如果我正确的话,Oracle JDBC驱动程序还是有点麻烦的。 MySQL和DB2已经支持它很久了。 PostgreSQL在不久之前开始支持它。 没有MSSQL的措辞,因为我从来没有使用它。

对于Oracle,您可以在同一个事务中的INSERT之后直接CallableStatement具有RETURNING子句或SELECT CURRVAL(sequencename)CallableStatement (或任何特定于DB的语法来执行此操作)以获取最后生成的密钥。 另请参阅此答案 。

我正从基于单线程的基于JDBC的应用程序中打击Microsoft SQL Server 2008 R2,并且不使用RETURN_GENERATED_KEYS属性或任何PreparedStatement就拉回最后一个ID。 看起来像这样:

 private int insertQueryReturnInt(String SQLQy) { ResultSet generatedKeys = null; int generatedKey = -1; try { Statement statement = conn.createStatement(); statement.execute(SQLQy); } catch (Exception e) { errorDescription = "Failed to insert SQL query: " + SQLQy + "( " + e.toString() + ")"; return -1; } try { generatedKey = Integer.parseInt(readOneValue("SELECT @@IDENTITY")); } catch (Exception e) { errorDescription = "Failed to get ID of just-inserted SQL query: " + SQLQy + "( " + e.toString() + ")"; return -1; } return generatedKey; } 

这个博客很好地隔离了三个主要的SQL Server“最后的ID”选项: http : //msjawahar.wordpress.com/2008/01/25/how-to-find-the-last-identity-value-inserted-in-the -sql-server / – 还不需要另外两个。

  1. 创build生成的列

     String generatedColumns[] = { "ID" }; 
  2. 把这个生成的列传给你的陈述

     PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns); 
  3. 使用ResultSet对象来获取Statement上的GeneratedKeys

     ResultSet rs = stmtInsert.getGeneratedKeys(); if (rs.next()) { long id = rs.getLong(1); System.out.println("Inserted ID -" + id); // display inserted record } 

根据使用Statement.RETURN_GENERATED_KEYS “不支持的function”错误,试试这个:

  String[] returnId = { "BATCHID" }; String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')"; PreparedStatement statement = connection .prepareStatement(sql, returnId); int affectedRows = statement.executeUpdate(); if (affectedRows == 0) { throw new SQLException("Creating user failed, no rows affected."); } try (ResultSet rs = statement.getGeneratedKeys()) { if (rs.next()) { System.out.println(rs.getInt(1)); } rs.close(); } 

BRANCHID是自动生成的ID

我正在使用SQLServer 2008,但我有一个发展限制:我不能使用新的驱动程序,我不得不使用“com.microsoft.jdbc.sqlserver.SQLServerDriver”(我不能使用“com.microsoft.sqlserver.jdbc .SQLServerDriver“)。

这就是为什么解决schemeconn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)为我抛出一个java.lang.AbstractMethodError 。 在这种情况下,我发现一个可能的解决scheme是Microsoft提出的旧方法: 如何使用JDBC检索@@ IDENTITY值

 import java.sql.*; import java.io.*; public class IdentitySample { public static void main(String args[]) { try { String URL = "jdbc:microsoft:sqlserver://yourServer:1433;databasename=pubs"; String userName = "yourUser"; String password = "yourPassword"; System.out.println( "Trying to connect to: " + URL); //Register JDBC Driver Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); //Connect to SQL Server Connection con = null; con = DriverManager.getConnection(URL,userName,password); System.out.println("Successfully connected to server"); //Create statement and Execute using either a stored procecure or batch statement CallableStatement callstmt = null; callstmt = con.prepareCall("INSERT INTO myIdentTable (col2) VALUES (?);SELECT @@IDENTITY"); callstmt.setString(1, "testInputBatch"); System.out.println("Batch statement successfully executed"); callstmt.execute(); int iUpdCount = callstmt.getUpdateCount(); boolean bMoreResults = true; ResultSet rs = null; int myIdentVal = -1; //to store the @@IDENTITY //While there are still more results or update counts //available, continue processing resultsets while (bMoreResults || iUpdCount!=-1) { //NOTE: in order for output parameters to be available, //all resultsets must be processed rs = callstmt.getResultSet(); //if rs is not null, we know we can get the results from the SELECT @@IDENTITY if (rs != null) { rs.next(); myIdentVal = rs.getInt(1); } //Do something with the results here (not shown) //get the next resultset, if there is one //this call also implicitly closes the previously obtained ResultSet bMoreResults = callstmt.getMoreResults(); iUpdCount = callstmt.getUpdateCount(); } System.out.println( "@@IDENTITY is: " + myIdentVal); //Close statement and connection callstmt.close(); con.close(); } catch (Exception ex) { ex.printStackTrace(); } try { System.out.println("Press any key to quit..."); System.in.read(); } catch (Exception e) { } } } 

这个解决scheme为我工作!

我希望这有帮助!

 Connection cn = DriverManager.getConnection("Host","user","pass"); Statement st = cn.createStatement("Ur Requet Sql"); int ret = st.execute();