Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the last record number after inserting record to database in access

i have database in access with auto increase field (ID).

i insert record like this (in C#)

SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();

how to get the last inserting number ?

i dont want to run new query i know that in sql there is something like SELECT @@IDENTITY

but i dont know how to use it

thanks in advance

like image 999
Gali Avatar asked Aug 29 '11 12:08

Gali


People also ask

How do I find the last record in Access?

In MS Access, the Last() function is used to return a field value from the last record in the result set returned by a query.

How can we view last record added to a table?

We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table. And then we can select the entry which we want to retrieve.

How can I get the latest record in database based on datetime?

if you need by other column datetime then you can use ->orderBy('columnName','desc/asc')->get() otherwise you can use latest() function.

Where is a new record added in Access?

On the Home tab, in the Records group, click New, or click New (blank) record, or press Ctrl+Plus Sign (+). Find the record with an asterisk in the record selector, and enter your new information. Click or otherwise place the focus on the first field that you want to use, and then enter your data.


2 Answers

More about this : Getting the identity of the most recently added record

The Jet 4.0 provider supports @@Identity

string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select @@Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
  using (OleDbCommand cmd = new OleDbCommand(query, conn))

  {
    cmd.Parameters.AddWithValue("", Category.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
    cmd.CommandText = query2;
    ID = (int)cmd.ExecuteScalar();
  }
}
like image 195
Pranay Rana Avatar answered Oct 11 '22 01:10

Pranay Rana


I guess you could even write an extension method for OleDbConnection...

public static int GetLatestAutonumber(
    this OleDbConnection connection)
{
    using (OleDbCommand command = new OleDbCommand("SELECT @@IDENTITY;", connection))
    {
        return (int)command.ExecuteScalar();
    }
}
like image 5
Lee.J.Baxter Avatar answered Oct 10 '22 23:10

Lee.J.Baxter