using System;
using System.Data.Common;using System.Linq;using Dapper;using MySql.Data.MySqlClient;public class DapperBasewhere T:class,new() { /// /// 读连接 /// ///public DbConnection GetWriteConnection() { MySqlConnection connection = new MySqlConnection(WebconfigUtils.GetWriteDbconfig()); //NpgsqlConnection connection = new NpgsqlConnection(_sqlconnection); connection.Open(); return connection; } /// /// 读连接 /// ///public DbConnection GetReadConnection() { try { MySqlConnection connection = new MySqlConnection(WebconfigUtils.GetReadDbconfig()); connection.Open(); return connection; } catch (Exception) { return GetWriteConnection(); } } public T ExecuteSql(string sql, object obj) { using (var connection = GetReadConnection()) { var model = connection.Query (sql, obj) .FirstOrDefault(); connection.Close(); return model; } } /// /// 事务执行sql /// /// /// ///public int ExecuteTransactionSql(string sql, object obj) { using (var connection = GetWriteConnection()) { var trans = connection.BeginTransaction(); var rows =connection.Execute(sql, obj,trans); if (rows > 0) { trans.Commit(); } else { trans.Rollback(); } connection.Close(); return rows; } } }