Jump to content

saber o ID da linha inserida na base de dados.


Paulo_Rocha

Recommended Posts

Boas pessoal,

Eu necessito de saber o ID da linha que estou a inserir na base de dados.

imaginemos que eu estou a utilizar algo do genero :

OleDbConnection Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Application.StartupPath + "\\BD.mdb");

string query = "INSERT INTO Clientes([Nome], [Empresa]) VALUES (@Nome, @Empresa)";

OleDbCommand command = new OleDbCommand(query, Connection);

command.Parameters.Add("@Nome", OleDbType.VarChar).Value = NomeTextbox.Text;
command.Parameters.Add("@Empresa", OleDbType.VarChar).Value = EmpresaTextbox.Text;

Connection.Open();

int x = command.ExecuteNonQuery();

if (x < 1)
{
   MessageBox.Show("Erro ao inserir", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
   MessageBox.Show("Registo inserido com sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Connection.Close();
command = null;

Como consigo saber o ID?

Link to comment
Share on other sites

Boas kingpito,

Em relação ao código que enviaste já testei e não está a funcionar aquela parte da query dá erro.

no entanto encontrei uma outra solução que já testei e funciona.

cmdIns.Parameters.Clear();
cmdIns.CommandText = "SELECT @@IDENTITY";

// Get the last inserted id.
int insertID = Convert.ToInt32( cmdIns.ExecuteScalar() );

Obrigado

Cumprimentos

Paulo Rocha

Link to comment
Share on other sites

  • 1 month later...

Olá,

Atenção que @@IDENTITY pode retornar valores que poderão não ser os que pretendes.

Sugiro a leitura deste artigo:

http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

Pedro Martins

Sharing is Knowledge!

http://www.linkedin.com/in/rechousa

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.