How to get the insert ID in JDBC?

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

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

提交回复
热议问题