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

C# MySql Transaction Async的更多相关文章

  1. MySQL transaction

    MySQL transaction(数据库的事务) 数据库事务(Database Transaction),是指作为单个逻辑工作单元执行的一系列操作. 要么完全执行,要么完全地不执行. ACID 事务 ...

  2. mysql transaction 事务

    1.事务简介 一个"最小的"不可再分的"工作单元". 一个事务通常对应了一个完整的业务.如:银行的转账功能,a转账给b,a扣钱,b加钱. 一个事务包含一条或多条 ...

  3. NodeJs使用Mysql模块实现事务处理

    依赖模块: 1. mysql:https://github.com/felixge/node-mysql npm install mysql --save 2. async:https://githu ...

  4. MySQL监控模板说明-Percona MySQL Monitoring Template for Cacti

    http://blog.chinaunix.net/uid-16844903-id-3535535.html https://www.percona.com/doc/percona-monitorin ...

  5. Percona监控MySQL模板详解

    InnoDB Adaptive Hash Index 显示了"自适应哈希索引"的使用情况,哈希索引只能用来搜索等值的查询. # Hash table size 17700827, ...

  6. node封装mysql操作

    前言 node是基于异步的,因此在进行数据库查询操作的通常是通过回调来操作查询结果.但是在有了es7的async/await,基本不再需要回调了,所以本篇是基于async/await对mysql进行一 ...

  7. 数据库选型之MySQL(多线程并发)

    刘勇    Email: lyssym@sina.com 本博客记录作者在工作与研究中所经历的点滴,一方面给自己的工作与生活留下印记,另一方面若是能对大家有所帮助,则幸甚至哉矣! 简介 鉴于高频中心库 ...

  8. node.js 调用mysql 数据库

    1.在package.json中添加mysql依赖 命令:npm install mysql --save 2.项目中添加mysql文件夹 > 文件夹下创建config文件夹,并在config下 ...

  9. python操作MySQL数据库的三个模块

    python使用MySQL主要有两个模块,pymysql(MySQLdb)和SQLAchemy. pymysql(MySQLdb)为原生模块,直接执行sql语句,其中pymysql模块支持python ...

随机推荐

  1. 2019-11-28:ssrf基础学习,笔记

    ssrf服务端请求伪造ssrf是一种由恶意访问者构造形成由服务端发起请求的一个安全漏洞,一般情况下,ssrf访问的目标是从外网无法访问的内部系统,正式因为它是由服务端发起的,所以它能请求到它相连而外网 ...

  2. 面试官:CPU百分百!给你一分钟,怎么排查?有几种方法?

    Part0 遇到了故障怎么办? 在生产上,我们会遇到各种各样的故障,遇到了故障怎么办? 不要慌,只有冷静才是解决故障的利器. 下面以一个例子为例,在生产中碰到了CPU 100%的问题怎么办? 在生产中 ...

  3. day 19 os模块的补充 序列化 json pickle

    os   模块 os.path.abspath  规范绝对路径 os.path.split() 把路径分成两段,第二段是一个文件或者是文件夹 os.path.dirname    取第一部分 os.p ...

  4. es6 filter方法应用

    let arr =[ {title:'aaaa',read:100,hot:true}, {title:'bbbb',read:50,hot:false}, {title:'ccc',read:100 ...

  5. 天了噜,为什么外链css要放在头部,js要放在尾部?

    我们最开始学前端的时候都会看到教程在处理外部css,js的时候会将css放在header中,js放在body的最后.为什么要这样子处理,今天参考一些资料好好分析下. 为什么外链css为什么要放头部? ...

  6. Airtest介绍与脚本入门

    前言 通过阅读本小节教程,你将了解以下内容: 一个Airtest脚本例子的详细解析 如何在Python脚本中调用Airtest接口 图片语句的参数介绍 Airtest介绍 Airtest是一款基于Py ...

  7. Linux查看系统基本信息、版本信息等

    Linux下如何查看版本信息, 包括位数.版本信息以及CPU内核信息.CPU具体型号 1.uname -a   (Linux查看版本当前操作系统内核信息) 2.cat /proc/version (L ...

  8. Hadoop streaming脚本中约束关系参数详解

    1 -D mapred.output.key.comparator.class=org.apache.hadoop.mapred.lib.KeyFieldBasedComparator \ 2 -D ...

  9. SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”

    1.问题描述: 我的项目是tcServer,在运行的之后出现如下错误: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBin ...

  10. java this,super简单理解

    *****this****** 表示对当前对象的引用. 作用:1.区分实例变量和局部变量(this.name----->实例变量name) 2.将当前对象当做参数传递给其它对象和方法.利用thi ...