C# MySql Transaction Async
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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现