欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# MySql Transaction Async

程序员文章站 2022-04-14 19:38:20
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Co... ......
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;            
        }