C# MySql Transaction Async

时间:2021-07-08 07:01:51

 static async Task<int> MySqlWriteAsync(string writeSQL,Dictionary<string,object> parametersDic=null)
        {
            int executeResult = -1;
            using (MySqlConnection conn = GetMySqlConnection())
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }

                using (MySqlCommand cmd = new MySqlCommand(writeSQL, conn))
                {
                    using (MySqlTransaction myTrans = await conn.BeginTransactionAsync())
                    {
                        try
                        {
                            if (parametersDic != null && parametersDic.Any())
                            {
                                foreach (var pDic in parametersDic)
                                {
                                    cmd.Parameters.AddWithValue(pDic.Key, pDic.Value);
                                }
                            }

                            cmd.Transaction = myTrans;
                            executeResult = await cmd.ExecuteNonQueryAsync();
                            myTrans.Commit();
                        }
                        catch (Exception ex)
                        {
                            myTrans.Rollback();
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
            return executeResult;            
        }