ADO.NET - Updating Multiple DataTables

前端 未结 1 453
忘掉有多难
忘掉有多难 2020-12-12 05:49

So I have some code like this:

        DataSet dataSet = new DataSet();            
        DataTable dataTable1 = new DataTable(\"Table1\");
        DataTab         


        
相关标签:
1条回答
  • 2020-12-12 06:14

    You can pass a dataset into a DataAdapter's Update statement, which will update all of the tables in the dataset. UPDATE: No, it doesn't. DataAdapters always update only one table. The overload to Update() that takes a DataSet as its parameter, from the MSDN documentation, "Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet from a DataTable named "Table"." Sorry for the confusion. The rest of the answer is still valid, though.

    If you want to assure that all the updates succeed or fail as an atomic unit, use the SqlTransaction object:

    DataSet ds = new DataSet();
    // do something with the dataset
    
    SqlDataAdapter dataAdapter = new SqlDataAdapter();
    SqlConnection cn = new SqlConnection(connString);
    cn.Open();
    
    SqlTransaction trans = cn.BeginTransaction();
    
    SqlDataAdapter dataAdapter = new SqlDataAdapter();
    
    // set the InsertCommand, UpdateCommand, and DeleteCommand for the data adapter
    
    dataAdapter.InsertCommand.Transaction = trans;
    dataAdapter.UpdateCommand.Transaction = trans;
    dataAdapter.DeleteCommand.Transaction = trans;
    
    try
    {
        dataAdapter.Update( ds );
        trans.Commit();
    }
    catch
    {
        trans.Rollback();
    }
    
    cn.Close();
    
    0 讨论(0)
提交回复
热议问题