How to use db transcation for an OleDb token places in a loop?

  • Thread starter Thread starter ThankfulHeart
  • Start date Start date
T

ThankfulHeart

Guest
There comes an interesting problem for you, it seems very easy in code:

using (OleDbConnection con = new OleDbConnection(……))
{

OleDbCommand cmd = new OleDbCommand(con);
OleDbTranscation trans = con.BeginTranscation();
cmd.CommandText = "update xxx set field1=@field1,field2=@field2 where field3=@field3";

//Suppose "pCollection" is a collection variable defined before, and this is a stack type.

Point p = pCollection.Pop();

while(pCollection.Count!=0)
{
cmd.Parameters["@field1"].Value = p.Field1;
cmd.Parameters["@field2"].Value = p.Field2;
cmd.Parameters["@field3"].Value = p.Field3;
cmd.Parameters["@field4"].Value = p.Field4;
p = pCollection.Pop();
cmd.ExecuteNonQuery();
}
trans.Commit();
}


The codes above seems roughly right, however if you run it and you will find that only the last record is updated, because the parameters of SqlCommand are overridden by the latter time of loop, and all the previous loops parameters are referring to the same parameters of SqlCommand, so only the last time the parameters values take action. And all the transcations are pointing to the last time of updating record.So my question is How to make each updating statement takes action within the whole transcation (each updating SQL has different values of parameters)?


ASP.NET Forum
Other Discussion Forums
FreeRice Donate
Issues to report
Free Tech Books Search and Download


Continue reading...
 
Back
Top