1

I am trying to get last auto number after inserting record into access database. I am getting zero. Not sure what I am doing wrong. I tried to google but could not find any simple example which I can use to understand.

// Database was opened before.
cmd.ExecuteNonQuery(); // Insert is working fine.
cmd = new OleDbCommand("SELECT @@IDENTITY", con);
id = cmd.ExecuteNonQuery(); // id shows zero in debug
Carl
  • 26,500
  • 4
  • 65
  • 86
user2026794
  • 123
  • 2
  • 13
  • 1
    Searching for [access SELECT @@IDENTITY](http://www.bing.com/search?q=access+SELECT+%40%40IDENTITY) - gives you [HOW TO: Retrieve the Identity Value While Inserting Records into Access Database By Using Visual Basic .NET](http://support.microsoft.com/kb/815629) - which uses `ExecuteScalar` instead of `ExecuteNonQuery` (which returns number of affected rows, not a result ). – Alexei Levenkov Jan 04 '14 at 03:47

3 Answers3

2

ExecuteNonQuery is meant for doing catalog type operations (creating/deleting objects and so forth) and update/insert/delete operations (note that select is not in that list).

For the update/insert/delete, it returns the number of rows affected.

If you want to select something from the database, you will need to get a result set to see what it returns (see ExecuteReader for example).

Altenatively, ExecuteScalar can execute a command and return the first column of the first row, which seems to be what you're after here.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

See this:

cn.Execute "INSERT INTO TheTable.....", , cmd+ adExecuteNoRecords
Set rs = cn.Execute("SELECT @@Identity", , cmd)
Community
  • 1
  • 1
0

If DAO use

RS.Move 0, RS.LastModified
lngID = RS!AutoNumberFieldName

If ADO use

cn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
Set rs = cn.Execute("SELECT @@Identity", , adCmdText)
Debug.Print rs.Fields(0).Value

cn being a valid ADO connection, @@Identity will return the last Identity (Autonumber) inserted on this connection.

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115