using System;
using System.Data.Common;
using System.Linq;
using Dapper;
using MySql.Data.MySqlClient;
public class DapperBase<T> where T:class,new()
{ /// <summary>
/// 读连接
/// </summary>
/// <returns></returns>
public DbConnection GetWriteConnection()
{
MySqlConnection connection = new MySqlConnection(WebconfigUtils.GetWriteDbconfig());
//NpgsqlConnection connection = new NpgsqlConnection(_sqlconnection);
connection.Open();
return connection;
} /// <summary>
/// 读连接
/// </summary>
/// <returns></returns>
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<T>(sql, obj)
.FirstOrDefault();
connection.Close();
return model;
}
} /// <summary>
/// 事务执行sql
/// </summary>
/// <param name="sql"></param>
/// <param name="obj"></param>
/// <returns></returns>
public int ExecuteTransactionSql(string sql, object obj)
{
using (var connection = GetWriteConnection())
{
var trans = connection.BeginTransaction();
var rows =connection.Execute(sql, obj,trans);
if (rows > )
{
trans.Commit();
}
else
{
trans.Rollback();
}
connection.Close();
return rows;
}
} }