How to get the insert ID in JDBC?

后端 未结 12 1759
暖寄归人
暖寄归人 2020-11-21 06:09

I want to INSERT a record in a database (which is Microsoft SQL Server in my case) using JDBC in Java. At the same time, I want to obtain the insert ID. How can

12条回答
  •  旧时难觅i
    2020-11-21 06:41

    I'm using SQLServer 2008, but I have a development limitation: I cannot use a new driver for it, I have to use "com.microsoft.jdbc.sqlserver.SQLServerDriver" (I cannot use "com.microsoft.sqlserver.jdbc.SQLServerDriver").

    That's why the solution conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) threw a java.lang.AbstractMethodError for me. In this situation, a possible solution I found is the old one suggested by Microsoft: How To Retrieve @@IDENTITY Value Using JDBC

    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)
            {
            }
        }
    }
    

    This solution worked for me!

    I hope this helps!

提交回复
热议问题