我想使用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();