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

天大地大妈咪最大 提交于 2020-01-01 02:36:07

问题


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


回答1:


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();
  }
}



回答2:


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();
    }
}



回答3:


I like more indicate the type of command is very similar to the good solution provided by Pranay Rana

using (OleDbCommand cmd = new OleDbCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = sql_Insert;
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = sql_obtainID;
                        resultado = (int)comando.ExecuteScalar();
                    }



回答4:


 query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
        ' Using cn As New SqlConnection(connect)

          Using cmd As New OleDb.OleDbCommand(query, cnPTA)
                cmd.Parameters.AddWithValue("@CategoryName", OleDb.OleDbType.Integer)
                If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
                ID = cmd.ExecuteNonQuery
          End Using



回答5:


Using @Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:

OleDbConnection con = new OleDbConnection(string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT @@IDENTITY;", con))
{
    ReturnIDCast =(int)command.ExecuteScalar();
}

NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.



来源:https://stackoverflow.com/questions/7230200/how-to-get-the-last-record-number-after-inserting-record-to-database-in-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!