使用ADO.NET返回最后插入的记录 [英] Return last inserted record using ADO.NET
问题描述
我有以下代码
public void addSeesion(int userid)
{
string qry =插入Session_Info(Session_Id,User_Id)值(@ SessionId,@ UserId);
MySqlCommand cmd = new MySqlCommand(qry,Connection.Get());
cmd.Parameters.AddWithValue(@ SessionId,session);
cmd.Parameters.AddWithValue(@ UserId,userid);
cmd.ExecuteNonQuery() ;
}
表中有3列包括主键。现在我想在此之后获取最后插入的记录而不进行新查询。 cmd.ExecuteScalar和cmd.LastInsertedId给出主键。
但我需要整行或Session_Id值。是真的有可能还是有其他方式???
我尝试过的事情:
cmd.ExecuteScalar和cmd.LastInsertedId给出主键。
但我想要整个记录。
I have the below code
public void addSeesion(int userid)
{
string qry = "insert into Session_Info(Session_Id,User_Id)values(@SessionId,@UserId)";
MySqlCommand cmd = new MySqlCommand(qry, Connection.Get());
cmd.Parameters.AddWithValue("@SessionId", session);
cmd.Parameters.AddWithValue("@UserId", userid);
cmd.ExecuteNonQuery();
}
There are 3 columns in the table including primary key. Now I want to get the last inserted record after this without making a new query. cmd.ExecuteScalar and cmd.LastInsertedId gives the primary key.
But I need the entire row or the Session_Id value. Is it really possible or there have any other way???
What I have tried:
cmd.ExecuteScalar and cmd.LastInsertedId gives the primary key.
But i want the entire record.
推荐答案
我这样做的方法很简单:添加一个名为InsertAt的DATETIME列,并将其默认值设置为GETDATE()
然后,您所要做的就是:
The way I would do it is simple: add a DATETIME column called InsertAt and set it's default value to GETDATE()
Then, all you have to do is:
SELECT TOP 1 * FROM MyTable ORDER BY InsertAt DESC
因为您已经给它一个默认值,所以其他代码都不需要更改。
Because you have given it a default, no other code should need changes.
这篇关于使用ADO.NET返回最后插入的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!