各位大侠:
    小弟需要通过一个循环来向数据中插入数据,但是不知道如何编写事务:请多多教导:
for(int i=0;i<strAv.Length;i++)
{
    if(CheckNowTime(strAv[i].ToString().Trim())) {
  strError+=strAt[i].ToString()+"\"";
}
}
strAv,strAt为数组;CheckNowTime(string str);是一个方法:以(存储过程)来完成数据插入&&同时返回一个bool值用来判断;小弟不知到如何定义事务来确保数据的完整性(确保循环中的数据都能够完成,有一次循环出了问题,则改次数据的插入无效)
希望各位大哥能帮写得详细些,给点例子,小弟在这里先谢谢拉~~:)

解决方案 »

  1.   

    在.net1.1里楼主的问题比较难于解决,我所知道的方法是先把修改放在内存表中,全部成功以后,使用transaction一次性的update.
    在.net2.0里有一个类 TransactionScope .可以用来标志一块代码参与一个事务,你不需要在数据库操作中直接使用事务本身。TransactionScope会帮助自动你管理周边事务,用起来相当容易。
    看看这个例子就明白了。
    using (TransactionScope ts = new TransactionScope())
    {
        //Create and open the SQL connection.  The work done on this connection will be a part of the transaction created by the TransactionScope
        SqlConnection myConnection = new SqlConnection("server=(local)\\SQLExpress;Integrated Security=SSPI;database=northwind");
        SqlCommand myCommand = new SqlCommand();
        myConnection.Open();
        myCommand.Connection = myConnection;    //Restore database to near it's original condition so sample will work correctly.
        myCommand.CommandText = "DELETE FROM Region WHERE (RegionID = 100) OR (RegionID = 101)";
        myCommand.ExecuteNonQuery();    //Insert the first record.
        myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'MidWestern')";
        myCommand.ExecuteNonQuery();    //Insert the second record.
        myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'MidEastern')";
        myCommand.ExecuteNonQuery();    myConnection.Close();                    //Call complete on the TransactionScope or not based on input
        ConsoleKeyInfo c;
        while (true)
        {
                                Console.Write("Complete the transaction scope? [Y|N] ");
            c = Console.ReadKey();
            Console.WriteLine();        if ((c.KeyChar == 'Y') || (c.KeyChar == 'y'))
            {
                // Commit the transaction
                ts.Complete();
                break;
            }
            else if ((c.KeyChar == 'N') || (c.KeyChar == 'n'))
            {
                break;
            }
        }呵呵。
      

  2.   

    使用TransactionScope,楼主的问题将迎刃而解~~~~```
      

  3.   

    我也遇到这样的问题 
    不知道怎么解决 
    很不幸得是我用的是 .net1.1期待中。