Skip to content

Insert Ignore LastInsertedId is -1 when Ignored #1147

@mkehoe

Description

@mkehoe

Software versions
MySqlConnector version: 2.1.7
Server type (MySQL, MariaDB, Aurora, etc.) and version: MySql 5.7
.NET version: 6.0

Describe the bug
When using an insert ignore statement with ExecuteNonQueryAsync(), LastInsertedId is -1 (expected 0) if the insert is ignored. I believe this is changed behavior from an earlier version.

Code sample

await connection.OpenAsync();

var sql = @"insert ignore into test.test_table (id, foo) values (@id, @foo)";
await using var cmd = new MySqlCommand(sql, connection);

cmd.Parameters.AddWithValue("@id", 2);
cmd.Parameters.AddWithValue("@foo", "Test");

cmd.CommandType = System.Data.CommandType.Text;
await cmd.ExecuteNonQueryAsync();

Expected behavior
MySqlConnector docs for LastInsertedId reference MySql LAST_INSERTED_ID() and they state:

If you use INSERT IGNORE and the row is ignored, the LAST_INSERT_ID() remains unchanged from the current value (or 0 is returned if the connection has not yet performed a successful INSERT)

This statement leads me to believe that 0 for LastInsertedId is correct in this scenario.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions