简体   繁体   中英

Getting a new record id return value from a stored procedure in Java

I need to create a new record in a stored procedure and return the ID of the inserted record. I'm sure this is quite simple but I don't know the right way to do this...

I've created a simple stored procedure that requires 3 parameters, inserts a record and returns a value of the inserted record:

ALTER PROCEDURE [dbo].[BronzeLabsCreateServiceEquipment]
    @companyID int = null,
    @manufacturerID int = null,
    @modelID int = null,
    @serialNumber varchar(255) = '',
    @machine varchar(255) = '',
    @location varchar(255) = ''
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO ServiceEquipment(CompanyID, ManufacturerID, ModelID, SerialNumber, Machine, Location)
    VALUES (@companyID, @manufacturerID, @modelID, @serialNumber, @machine, @location)

    Declare @new_identity int;
    SELECT @new_identity = SCOPE_IDENTITY()
    return @new_identity

END

Then I try to call this in Java

String queryStringAlt = "CALL dbo.BronzeLabsCreateServiceEquipment(?, ?, ?, ?, ?, ?)";
CallableStatement cs = conn.prepareCall(queryStringAlt); 

    cs.setString(1, null);
    cs.setString(2, null);
    cs.setString(3, null);
    cs.setString(4, "new123-1");
    cs.setString(5, "new123-2");
    cs.setString(6, "new123-3");

ResultSet rs = cs.executeQuery();

...however the prepared statement doesn't return a resultset so that last line doesn't work. What does it return and how do I get it? Or am I doing the wrong thing here - should I be using output parameters (which I tried but had a syntax issue I couldn't get to the bottom of).

Thanks for your help. I hadn't thought of putting the identity into a resultset, So the new code is:

Stored procedure

ALTER PROCEDURE [dbo].[BronzeLabsCreateServiceEquipment]
    @companyID int = null,
    @manufacturerID int = null,
    @modelID int = null,
    @serialNumber varchar(255) = '',
    @machine varchar(255) = '',
    @location varchar(255) = ''
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO ServiceEquipment(CompanyID, ManufacturerID, ModelID, SerialNumber, Machine, Location)
    VALUES (@companyID, @manufacturerID, @modelID, @serialNumber, @machine, @location)

    SELECT SCOPE_IDENTITY() AS equipmentID

END

Java code

String queryStringAlt = "CALL dbo.BronzeLabsCreateServiceEquipment(?, ?, ?, ?, ?, ?)";
CallableStatement cs = conn.prepareCall(queryStringAlt); 

    cs.setString(1, null);
    cs.setString(2, null);
    cs.setString(3, null);
    cs.setString(4, "new123-1");
    cs.setString(5, "new123-2");
    cs.setString(6, "new123-3");

ResultSet rs = cs.executeQuery();
if(rs.next()) {
    System.out.println("Equipment ID: " + rs.getString("equipmentID"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM