how to use sqltransaction in c#

前端 未结 6 2116
执笔经年
执笔经年 2020-12-05 10:56

I am using following code to execute two commands at once. I used sqltransaction to assure either all command get executed or rolled back.When I run my program without \"tra

6条回答
  •  情深已故
    2020-12-05 11:11

    Update or Delete with sql transaction

     private void SQLTransaction() {
       try {
         string sConnectionString = "My Connection String";
         string query = "UPDATE [dbo].[MyTable] SET ColumnName = '{0}' WHERE ID = {1}";
    
         SqlConnection connection = new SqlConnection(sConnectionString);
         SqlCommand command = connection.CreateCommand();
         connection.Open();
         SqlTransaction transaction = connection.BeginTransaction("");
         command.Transaction = transaction;
         try {
           foreach(DataRow row in dt_MyData.Rows) {
             command.CommandText = string.Format(query, row["ColumnName"].ToString(), row["ID"].ToString());
             command.ExecuteNonQuery();
           }
           transaction.Commit();
         } catch (Exception ex) {
           transaction.Rollback();
           MessageBox.Show(ex.Message, "Error");
         }
       } catch (Exception ex) {
         MessageBox.Show("Problem connect to database.", "Error");
       }
     }
    

提交回复
热议问题