M
mycwcgr_new
Unregistered / Unconfirmed
GUEST, unregistred user!
C#中,在多人使用的网络环境中,使用事务能否保证得到最后插入记录的ID号?
在数据库中,有一个自动增加ID字段,在插入一条记录后,我想确保得到最后插入记录的ID号(在多人使用的网络环境中,可能有多人同时插入记录),
使用下面的事务处理是否可行?
OleDbConnection myOleDbConnection=null;
OleDbTransaction trans=null;
try
{
myOleDbConnection=ConstClass.GetDatabaseConnect();
myOleDbConnection.Open();
trans=myOleDbConnection.begin
Transaction();
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();
}
在数据库中,有一个自动增加ID字段,在插入一条记录后,我想确保得到最后插入记录的ID号(在多人使用的网络环境中,可能有多人同时插入记录),
使用下面的事务处理是否可行?
OleDbConnection myOleDbConnection=null;
OleDbTransaction trans=null;
try
{
myOleDbConnection=ConstClass.GetDatabaseConnect();
myOleDbConnection.Open();
trans=myOleDbConnection.begin
Transaction();
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();
}