C#中,在多人使用的网络环境中,使用事务能否保证得到最后插入记录的ID号?

mycuiwei 2005-04-27 10:59:00
C#中,在多人使用的网络环境中,使用事务能否保证得到最后插入记录的ID号?

在数据库中,有一个自动增加ID字段,在插入一条记录后,我想确保得到最后插入记录的ID号(在多人使用的网络环境中,可能有多人同时插入记录),
使用下面的事务处理是否可行?



OleDbConnection myOleDbConnection=null;
OleDbTransaction trans=null;
try
{

myOleDbConnection=ConstClass.GetDatabaseConnect();
myOleDbConnection.Open();

trans=myOleDbConnection.BeginTransaction();

OleDbCommand myCommand=new OleDbCommand();
myCommand.Connection=myOleDbConnection;
myCommand.Transaction=trans;
myCommand.CommandText="Insert into "+this.tableName+" (UserID,Name,ParentID,ElderBrotherID,YoungerBrotherID) values ("
+myTreePar.userID+","
+"'"+name+"',"
+parentID+","
+currentID+","
+nextID
+")";
myCommand.ExecuteNonQuery();



myCommand.CommandText="select max(NodeID) from "+this.tableName;
insertId=(int)myCommand.ExecuteScalar();

trans.Commit();

MessageBox.Show(insertId.ToString() +"cw");


}
catch(Exception e)
{
trans.Rollback();
}
finally
{
myOleDbConnection.Close();
}

...全文
112 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
S.F. 2005-04-28
  • 打赏
  • 举报
回复
ACCESS ??你用表登记吧;2个字段;1个真实字段一个临时字段;client new 单据的时候申请临时id,临时id++;保存的时候开启事务从真实id获取;这样保证了每个client获取id的时候都是不一样的,而且数据表写入的时候都是唯一的。
mycuiwei 2005-04-28
  • 打赏
  • 举报
回复
who know
mycuiwei 2005-04-27
  • 打赏
  • 举报
回复
是Access数据库,
popcorn 2005-04-27
  • 打赏
  • 举报
回复
使用"select @@identity from table"而非"max(NodeID) "

111,120

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧