If the command doesn't perform an insertion into a table that contains an AUTO_INCREMENT field the value of InsertId won't be defined.
When several rows are inserted, value of InsertId depends on FetchAll property. If FetchAll property is false, InsertId returns value for the first inserted row, otherwise it returns value for the last inserted row.
static void GetLastId(MySqlConnection myConnection) { MySqlCommand myCommand = new MySqlCommand("INSERT INTO Test.Dept (DeptNo, DName, Loc) VALUES (Null, 'AnotherOne', 'SomeWhere')", myConnection); myConnection.Open(); try { myCommand.ExecuteNonQuery(); Console.WriteLine(myCommand.InsertId); } finally { myConnection.Close(); } }
Public Sub GetLastId(ByVal myConnection As MySqlConnection) Dim myCommand As New MySqlCommand("INSERT INTO Test.Dept (DeptNo, DName, Loc) VALUES (Null, 'AnotherOne', 'SomeWhere')", myConnection) myConnection.Open() Try myCommand.ExecuteNonQuery() Console.WriteLine(myCommand.InsertId) Finally myConnection.Close() End Try End Sub
Target Platforms: Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2