How to use Scope_identify to return id . NET

Asked

Viewed 142 times

1

I am developing an application and need that when sql does the Insert return the value of the id that was inserted, I am using the following command

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)", con);
            cmd.ExecuteNonQuery();

I searched in some tutorials and found the Scope_identify function but how should I implement in my code?

1 answer

2

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

  • @Marconi must have seen tutorials of SQL Server. But tagged the question with MySql.

  • 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.

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.