Skip to content

Commit 1ed161f

Browse files
Ananya2na-ji
andauthored
fix statement getGenerateKeys() throwing an error is query starts with a comment (#2731)
close #2729 Co-authored-by: Naji Astier <[email protected]>
1 parent 1dc9eb7 commit 1ed161f

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -962,7 +962,7 @@ final void doExecuteStatement(StmtExecCmd execCmd) throws SQLServerException {
962962
// then add on the query to return them.
963963
if (RETURN_GENERATED_KEYS == execCmd.autoGeneratedKeys
964964
&& (EXECUTE_UPDATE == executeMethod || EXECUTE == executeMethod)
965-
&& sql.trim().toUpperCase().startsWith("INSERT")) {
965+
&& isInsert(sql)) {
966966
tdsWriter.writeString(IDENTITY_QUERY);
967967
}
968968

src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2749,6 +2749,31 @@ public void testExecuteUpdateInsertAndGenKeys() {
27492749
}
27502750
}
27512751

2752+
/**
2753+
* Tests executeUpdate for Insert with comments followed by getGenerateKeys
2754+
*
2755+
* @throws Exception
2756+
*/
2757+
@Test
2758+
public void testExecuteUpdateInsertWithCommentsAndGenKeys() {
2759+
try (Connection con = getConnection()) {
2760+
try(Statement stmt = con.createStatement()) {
2761+
String sql = "/* my comment */INSERT INTO " + tableName + " (NAME) VALUES('test')";
2762+
List<String> lst = Arrays.asList("ID");
2763+
String[] arr = lst.toArray(new String[0]);
2764+
stmt.executeUpdate(sql, arr);
2765+
try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
2766+
if (generatedKeys.next()) {
2767+
int id = generatedKeys.getInt(1);
2768+
assertEquals(id, 4, "id should have been 4, but received : " + id);
2769+
}
2770+
}
2771+
}
2772+
} catch (SQLException e) {
2773+
fail(TestResource.getResource("R_unexpectedException") + e.getMessage());
2774+
}
2775+
}
2776+
27522777
/**
27532778
* Tests executeUpdate using PreparedStatement for Insert followed by getGenerateKeys
27542779
*

0 commit comments

Comments
 (0)