using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Configuration; using System.Threading.Tasks; using Dapper; using MySql.Data.MySqlClient; using Winsoft.GOV.Framework.Model; namespace Winsoft.GOV.Framework.Provider { public abstract class BaseProvider { #region instance protected County _county; private static object lockObj = new object(); protected static void CreateInstance(ref K singleInstance) where K : BaseProvider, new() { if (singleInstance == null) { lock (lockObj) { if (singleInstance == null) { singleInstance = new K(); } } } } #endregion #region connection protected string connectionString; public BaseProvider(County county) { _county = county; connectionString = "gov_" + _county.ToString(); } /// /// /// /// protected IDbConnection GetDbConnection() { string connectionStr = ConfigurationManager.ConnectionStrings[connectionString].ConnectionString; var connection = new MySqlConnection { ConnectionString = connectionStr }; connection.Open(); return connection; } protected string BuildTotalSQL(string sql) { var selectCount = new StringBuilder("SELECT COUNT(1) from ("); return selectCount.Append(sql + ") as t") .ToString(); } /// /// /// /// /// 内部索引从0开始,页码从1开始 /// /// if (pageIndex - 1 >= 0) /// { /// pageIndex = pageIndex - 1; /// } /// /// /// /// /// protected PagedResult GetPagedList(string sql, int pageIndex, int pageSize, object param = null) { long total = 0; if (pageIndex < 0) { pageIndex = 0; } if (pageSize <= 0) { pageSize = 20; } using (IDbConnection connection = GetDbConnection()) { string totalSql = BuildTotalSQL(sql); total = connection.Query(totalSql, param).FirstOrDefault(); var list = connection.Query(String.Format(sql + " limit {0},{1}", pageIndex * pageSize, pageSize), param); return new PagedResult() { Data = list, Index = pageIndex, Size = pageSize, Total = total }; } } protected IEnumerable GetItemList(string sql, int itemIndex, int pageSize, object param = null) { if (itemIndex < 0) { itemIndex = 0; } if (pageSize <= 0) { pageSize = 20; } using (IDbConnection connection = GetDbConnection()) { var list = connection.Query(String.Format(sql + " limit {0},{1}", itemIndex, pageSize), param); return list; } } #endregion } }