SCOPE_IDENTITY is a SQL Server function. Accurate equivalent function for Mysql, last_insert_id:
SqlCommand cmd = new SqlCommand("insert into solicitacoes (assunto, mensagem, endereco, anexo, status, id_Departamento) values ('" + valorcadastro.assunto + "', '" + valorcadastro.mensagem + "', '" + valorcadastro.endereco + "','" + valorcadastro.anexo + "','Inicial', 0);SELECT last_insert_id()", con);
cmd.ExecuteNonQuery();
int ultimoRegistro = cmd.ExecuteScalar();
Note you need to use ExecuteScalar instead of ExecuteNonQuery to obtain the value returned by BD.
Or else, if you use class MySqlCommand, you can access the property LastInsertedId.
Note that your command is open to SQL injection attacks. You should use parameterized queries:
var cmd = new SqlCommand("insert into solicitacoes (assunto, mensagem, endereco, anexo, status, id_Departamento) values ('@assunto', '@mensagem', '@endereco','@anexo','Inicial', 0);SELECT last_insert_id()", con);
cmd.Parameters.AddWithValue("@assunto", valorcadastro.assunto);
cmd.Parameters.AddWithValue("@mensagem", valorcadastro.mensagem);
cmd.Parameters.AddWithValue("@endereco", valorcadastro.endereco);
cmd.Parameters.AddWithValue("@anexo", valorcadastro.anexo);
@Marconi Works in Mysql
– dcastro
@Marconi must have seen tutorials of SQL Server. But tagged the question with
MySql.– dcastro
As far as I know there is no ANSI SQL mechanism to generate keys automatically; you have to make this logic RDBMS by RDBMS even, unless you want to e.g. use Uuids as keys, in which case they can be generated by the application itself.
– user25930
A little warning, I think if there are competing scripts using the same Connection there could be problems. It is safe to always open a new connection when executing a command of this type and then close.
– RagnaRock