我想使用Java中的JDBC在數據庫(在個人狀況下爲Microsoft SQL Server)中INSERT
一條記錄。 同時,我想獲取插入ID。 如何使用JDBC API實現此目的? html
我正在使用SQLServer 2008,可是我有一個開發限制:我不能使用新的驅動程序,必須使用「 com.microsoft.jdbc.sqlserver.SQLServerDriver」(我不能使用「 com.microsoft.sqlserver.jdbc」 .SQLServerDriver」)。 java
這就是爲何解決方案conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
爲我拋出java.lang.AbstractMethodError的緣由。 在這種狀況下,我發現一種可能的解決方案是Microsoft建議的舊解決方案: 如何使用JDBC檢索@@ IDENTITY值 sql
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) { } } }
這個解決方案對我有用! 數據庫
我但願這有幫助! api
若是它是自動生成的密鑰,則能夠爲此使用Statement#getGeneratedKeys()
。 您須要在與用於INSERT
Statement
相同的Statement
上調用它。 首先,您須要使用Statement.RETURN_GENERATED_KEYS
建立Statement.RETURN_GENERATED_KEYS
以通知JDBC驅動程序返回鍵。 oracle
這是一個基本示例: sqlserver
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,由於我從未使用過它。 ui
對於Oracle,能夠在同一事務中的INSERT
以後直接使用RETURNING
子句或SELECT CURRVAL(sequencename)
(或執行此操做的任何特定於DB的語法SELECT CURRVAL(sequencename)
調用CallableStatement
,以獲取最後生成的密鑰。 另請參閱此答案 。 this
使用Statement.RETURN_GENERATED_KEYS
時遇到「不受支持的功能」錯誤,請嘗試如下操做: spa
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(); }
其中BATCHID
是自動生成的ID。
建立生成的列
String generatedColumns[] = { "ID" };
將今生成的列傳遞給您的聲明
PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
使用ResultSet
對象在Statement上獲取GeneratedKeys
ResultSet rs = stmtInsert.getGeneratedKeys(); if (rs.next()) { long id = rs.getLong(1); System.out.println("Inserted ID -" + id); // display inserted record }
Connection cn = DriverManager.getConnection("Host","user","pass"); Statement st = cn.createStatement("Ur Requet Sql"); int ret = st.execute();