How to get the insert ID in JDBC?

后端 未结 12 1712
暖寄归人
暖寄归人 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条回答
  • 2020-11-21 06:37

    It is possible to use it with normal Statement's as well (not just PreparedStatement)

    Statement statement = conn.createStatement();
    int updateCount = statement.executeUpdate("insert into x...)", Statement.RETURN_GENERATED_KEYS);
    try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
      if (generatedKeys.next()) {
        return generatedKeys.getLong(1);
      }
      else {
        throw new SQLException("Creating failed, no ID obtained.");
      }
    }
    
    0 讨论(0)
  • 2020-11-21 06:37

    In my case ->

    ConnectionClass objConnectionClass=new ConnectionClass();
    con=objConnectionClass.getDataBaseConnection();
    pstmtGetAdd=con.prepareStatement(SQL_INSERT_ADDRESS_QUERY,Statement.RETURN_GENERATED_KEYS);
    pstmtGetAdd.setString(1, objRegisterVO.getAddress());
    pstmtGetAdd.setInt(2, Integer.parseInt(objRegisterVO.getCityId()));
    int addId=pstmtGetAdd.executeUpdate();              
    if(addId>0)
    {
        ResultSet rsVal=pstmtGetAdd.getGeneratedKeys();
        rsVal.next();
        addId=rsVal.getInt(1);
    }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • If you are using Spring JDBC, you can use Spring's GeneratedKeyHolder class to get the inserted ID.

    See this answer... How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)

    0 讨论(0)
  • 2020-11-21 06:48

    You can use following java code to get new inserted id.

    ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
    ps.setInt(1, quizid);
    ps.setInt(2, userid);
    ps.executeUpdate();
    
    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        lastInsertId = rs.getInt(1);
    }
    
    0 讨论(0)
  • 2020-11-21 06:48
    Connection cn = DriverManager.getConnection("Host","user","pass");
    Statement st = cn.createStatement("Ur Requet Sql");
    int ret  = st.execute();
    
    0 讨论(0)
提交回复
热议问题