I have a Stored Procedure that look like this
BEGIN
insert into `TheSomaProject`.`Projects`
( `ProjectNr`, `MachineName`, `MachineNameEng`, `Type_Id`,
`SerialNr`, `Description`, `Created`, `CompanyId`, `MachineType` )
values
( param_ProjectNr, param_MachineName, param_MachineNameEng, param_TypeId,
param_Serial, param_Description, NOW(), param_CompId, param_MachineType);
SELECT last_insert_id();
END
But the return dosent give me the Id, it’s looks like this 0x00000000. The C# code look like this
MySqlDataReader Reader;
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = "CALL stp_InsertProject(@param_ProjectNr, @param_MachineName, @param_MachineNameEng, @param_TypeId, @param_Serial, @param_Description, @param_CompId, @param_MachineType);";
cmd.Parameters.AddWithValue("@param_ProjectNr", projectNr);
cmd.Parameters.AddWithValue("@param_MachineName", MachineName);
cmd.Parameters.AddWithValue("@param_MachineNameEng", MachineNameEng);
cmd.Parameters.AddWithValue("@param_TypeId", TypeId);
cmd.Parameters.AddWithValue("@param_Serial", SerialNr);
cmd.Parameters.AddWithValue("@param_Description", Description);
cmd.Parameters.AddWithValue("@param_CompId", CompanyId);
cmd.Parameters.AddWithValue("@param_MachineType", MachineType);
conn.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
Id = Convert.ToInt32(Reader["last_insert_id()"]);
}
conn.Close();
But if i try to use the same stp_InsertProject in phpMyAdmin i get the correct id back.
Your stored procedure does not return a result set with a column named ‘last_insert_id()’, thus using an
MySqlDataReaderwill not work (as you expect).Use
ExecuteScalar()to get the result. Note that the value returned is actually a 64-bit integer, so should use aInt64(orlong) type to hold the result:If you need to have a
Int32variable, and thus risk the overflow if too many rows are inserted, make sure you don’t directly cast toInt32(orint) as this will cause anInvalidCastExceptionsince the return type isn’t reallyInt32butInt64. In this case useConvert.ToInt32. But I would really suggest that you use a 64 bit integer.