如何在访问中将记录插入数据库后获取最后一个记录号

时间:2022-07-19 22:13:13

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

我有访问自动增加字段(ID)的数据库。

i insert record like this (in C#)

我插入这样的记录(在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

我不想运行新的查询我知道在sql中有类似SELECT @@ IDENTITY的东西

but i dont know how to use it

但我不知道如何使用它

thanks in advance

提前致谢

5 个解决方案

#1


13  

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

更多相关信息:获取最近添加的记录的标识

The Jet 4.0 provider supports @@Identity

Jet 4.0提供程序支持@@ 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


3  

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

我想你甚至可以为OleDbConnection写一个扩展方法......

public static int GetLatestAutonumber(
    this OleDbConnection connection)
{
    using (OleDbCommand command = new OleDbCommand("SELECT @@IDENTITY;", connection))
    {
        return (int)command.ExecuteScalar();
    }
}

#3


0  

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

我更喜欢指出命令的类型与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


0  

 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


0  

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:

使用@ Lee.J.Baxter的方法(这很好,因为其他人不适合我!)我逃脱了扩展方法,只是在表单内部添加内联:

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.

注意:在大多数情况下,您应该使用参数而不是我在这里使用的string.Format()方法。我刚刚这样做,因为它更快,我的插入值不是来自用户的输入,所以它应该是安全的。

#1


13  

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

更多相关信息:获取最近添加的记录的标识

The Jet 4.0 provider supports @@Identity

Jet 4.0提供程序支持@@ 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


3  

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

我想你甚至可以为OleDbConnection写一个扩展方法......

public static int GetLatestAutonumber(
    this OleDbConnection connection)
{
    using (OleDbCommand command = new OleDbCommand("SELECT @@IDENTITY;", connection))
    {
        return (int)command.ExecuteScalar();
    }
}

#3


0  

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

我更喜欢指出命令的类型与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


0  

 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


0  

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:

使用@ Lee.J.Baxter的方法(这很好,因为其他人不适合我!)我逃脱了扩展方法,只是在表单内部添加内联:

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.

注意:在大多数情况下,您应该使用参数而不是我在这里使用的string.Format()方法。我刚刚这样做,因为它更快,我的插入值不是来自用户的输入,所以它应该是安全的。