How to get the insert ID in JDBC?

后端 未结 12 1743
暖寄归人
暖寄归人 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:28

    I'm hitting Microsoft SQL Server 2008 R2 from a single-threaded JDBC-based application and pulling back the last ID without using the RETURN_GENERATED_KEYS property or any PreparedStatement. Looks something like this:

    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;
    } 
    

    This blog post nicely isolates three main SQL Server "last ID" options: http://msjawahar.wordpress.com/2008/01/25/how-to-find-the-last-identity-value-inserted-in-the-sql-server/ - haven't needed the other two yet.

提交回复
热议问题