2
    public int retrieveID()
    {
        int lastEntry = 0;
        try
        {
            queryString = "Select ID  from Database";
            myComm = new OleDbCommand(queryString, myConn);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return lastEntry;
    }

I want to retrieve the last primary key used in access database, whereas i set my primary key as autonumber.

elaborating more..

I am working on a database application and want to utilize the primary key, eg if the last entry in the database was 10, i want to retrieve 10, i tried simple query but that didnot work.

rummykhan
  • 2,603
  • 3
  • 18
  • 35

1 Answers1

1

If you are using an OLEDB connection then this should work

queryString = "SELECT @@IDENTITY";

Note that this should be called immediately after the INSERT that creates the record for which you want to save the ID value. If your code were to create other records with Identity (AutoNumber) fields then the @@IDENTITY value will be updated (replaced) by those calls.

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
  • Select max(id) from table, i think is a better way.. – rummykhan Apr 02 '13 at 20:33
  • 1
    @RummyKhan `SELECT Max(ID)` *can* be used in an app where you know **for certain** that there will only **ever** be **one user** using it, but it can cause serious problems in a multi-user environment and is a bad habit to acquire, especially since `SELECT @@IDENTITY` is available. – Gord Thompson Apr 02 '13 at 21:28
  • thanx bro.. i m still on static programming.. i've not yet started network programming.. however i will keep this thing in my mind.. thanx again.. – rummykhan Apr 03 '13 at 08:14