Question

I tried to return the id of the affected row I updated. I am wondering, why I don't get a ResultSet back from this (only primary key would be ok), eventhough I set Statement.RETURN_GENERATED_KEYS? I connect to a Microsoft SQL Server using the most recent jTDS driver 1.3.0.

    try
    {
        PreparedStatement pst = SQL.getConnection().prepareStatement(qry, Statement.RETURN_GENERATED_KEYS);

        pst.setString(1, someValue);
        pst.setString(2, someOtherValue);

        int affectedRows = pst.executeUpdate(); 
        System.out.println(affectedRows); //to make sure whether the query updated anything

        ResultSet rs = pst.getGeneratedKeys();

        if (rs.next())
        {
            System.out.println(rs.getInt(1));
        }
    } catch (Exception e) {
        e.printStacktTrace();
    }

Any suggestions here?

Was it helpful?

Solution

One workaround is to create a stored procedure and call it by using the CallableStatement method. Don't ask me why this works and not the other way though.

OTHER TIPS

With SQL Server 2008 and later you can use an OUTPUT clause in your INSERT or UPDATE statement. See this answer for an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top