• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#MySqlTransactionAsync

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;
using System.Data.Common;
using ConsoleApplication22.Model;
using System.Reflection;

namespace ConsoleApplication22
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadAsyncDemo();
            Console.ReadLine();
        }
       
        static async void ReadAsyncDemo()
        {
            string selectSQL = "select * from country";
            IList<Country> countryList = await MySqlRead2Async<Country>(selectSQL);
        }

        static string MySqlConnectionString = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString;
        static async void MySqlReadAsync(string readSQL,Dictionary<string,object> parametersDic=null)
        {
            using (MySqlConnection conn = GetMySqlConnection())
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
            
                using (MySqlCommand cmd = new MySqlCommand(readSQL, conn))
                {
                    using (DbDataReader dataReader = await cmd.ExecuteReaderAsync())
                    {
                        StringBuilder selectBuilder = new StringBuilder();
                        while (await dataReader.ReadAsync())
                        {                            
                            for(int i=0;i<dataReader.FieldCount;i++)
                            {
                                selectBuilder.Append(dataReader[i]+"\t");
                            }
                            selectBuilder.AppendLine();                                                       
                        }
                        Console.WriteLine(selectBuilder.ToString());
                    }
                }
            } 
        }

        static async Task<IList<T>> MySqlRead2Async<T>(string selectSQL,Dictionary<string,object> parametersDic=null)where T:class
        {
            IList<T> dataList = new List<T>();
            using (MySqlConnection conn = GetMySqlConnection())
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                using(MySqlCommand selectCmd=new MySqlCommand(selectSQL, conn))
                {
                    using (DbDataReader dataReaderAsync = await selectCmd.ExecuteReaderAsync())
                    {
                        if (dataReaderAsync.HasRows)
                        {
                            DataTable dt = new DataTable();
                            dt.Load(dataReaderAsync);
                            dataList = dt.ToDataList<T>();
                        }
                    }
                }
            }
            return dataList;               
        }

        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;            
        }

        static MySqlConnection GetMySqlConnection()
        {
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = MySqlConnectionString;
            return conn;
        }
    }

    static class ExtendClass
    {
        public static List<T> ToDataList<T>(this DataTable dt)
        {
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                T s = Activator.CreateInstance<T>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                    {
                        try
                        {
                            if (!Convert.IsDBNull(item[i]))
                            {
                                object v = null;
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                {
                                    v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                                }
                                else
                                {
                                    v = Convert.ChangeType(item[i], info.PropertyType);
                                }
                                info.SetValue(s, v, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                        }
                    }
                }
                list.Add(s);
            }
            return list;
        }
    }
}

 

 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;            
        }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
使用C#发送邮件支持ImplicitSSL发布时间:2022-07-14
下一篇:
MFCADO连接Oracle12c数据库客户端环境搭建发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap