/*********************************************************************************
** File Name : SQLConfig
** Copyright (C) 2013 guzhen.net. All Rights Reserved.
** Creator : SONGGUO\wangxiaoming
** Create Date : 2013/1/23 10:47:36
** Update Date :
** Description :
** Version No :
*********************************************************************************/
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;
using System.Runtime.Caching;
using System.IO; namespace System.Data
{
/// <summary>
/// 配置映射
/// </summary>
internal class SQLConfig
{
private ObjectCache _cache;
private string _configPath; /// <summary>
/// Constractor
/// </summary>
/// <param name="configPath">配置文件的路径</param>
public SQLConfig(string configPath = null)
{
if (configPath == null)
{
configPath = AppDomain.CurrentDomain.BaseDirectory + @"\DbSetting\";
} _cache = new MemoryCache(this.GetType().FullName);
_configPath = configPath;
} private void GenerateKey(MethodBase method, out string key)
{
key = method.DeclaringType.Name + "." + method.Name;
} private bool TryFindText(string key, out string text, out string configPath)
{
configPath = text = null;
foreach (string filePath in Directory.EnumerateFiles(_configPath, "*.config"))
{
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = filePath;
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var pair = config.AppSettings.Settings[key];
if (pair != null)
{
text = pair.Value;
configPath = filePath;
return true;
}
}
return false;
} /// <summary>
/// 获取调用的方法映射的SQL语句
/// </summary>
/// <param name="method">调用的方法</param>
/// <returns>SQL语句</returns>
/// <exception cref="Guzhen.Common.DbLiteException"></exception>
public string GetSQL(MethodBase method)
{
string key;
this.GenerateKey(method, out key);
string sql = (string)_cache[key], configPath;
if (sql == null)
{
if (!this.TryFindText(key, out sql, out configPath))
{
throw new InvalidOperationException(string.Format("没有配置{0}该项", key));
}
var policy = new CacheItemPolicy()
{
AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration,
//相对过期时间
SlidingExpiration = TimeSpan.FromMinutes(10D),
};
//监控配置文件变更
try
{
policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { configPath }));
}
catch (Exception ex)
{
App.LogError(ex, string.Format("ChangeMonitor:{0}", ex.Message));
}
_cache.Add(key, sql, policy);
}
return sql;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.Caching;
using System.Runtime.CompilerServices; namespace System.Data
{
/// <summary>
/// MultipleActiveResultSets=True;
/// </summary>
public class Database : IRequiresFactory
{
#region Static
internal const string ReturnParameterName = "@RETURN_VALUE";
internal const string DataTableName = "T";
private static SQLConfig Config; static Database()
{
Config = new SQLConfig();
}
#endregion #region Fields
private DbFactory _factory;
protected readonly ObjectCache Cache;
#endregion #region Properties
public virtual DbFactory Factory
{
get { return _factory; }
}
public bool SupportStoredProc
{
get { return Cache != null; }
}
#endregion #region Constructors
public Database(DbFactory factory, int? spCacheMemoryLimitMegabytes = null)
{
_factory = factory;
if (spCacheMemoryLimitMegabytes != null)
{
Cache = new MemoryCache(string.Format("Database[{0}]", factory.Name), new System.Collections.Specialized.NameValueCollection() { { "cacheMemoryLimitMegabytes", spCacheMemoryLimitMegabytes.Value.ToString() } });
}
}
#endregion #region NativeMethods
public DbCommand PrepareCommand(string text, CommandType type)
{
DbCommand cmd;
var scope = DbScope.Current;
if (scope != null)
{
cmd = scope.PrepareCommand(this);
cmd.CommandText = text;
}
else
{
cmd = _factory.CreateCommand(text);
}
cmd.CommandType = type;
return cmd;
} protected int ExecuteNonQuery(DbCommand cmd)
{
if (cmd.Connection == null)
{
cmd.Connection = _factory.CreateConnection();
}
bool isClosed = cmd.Connection.State == ConnectionState.Closed;
try
{
if (isClosed)
{
cmd.Connection.Open();
}
return cmd.ExecuteNonQuery();
}
finally
{
if (isClosed)
{
cmd.Connection.Close();
}
}
} protected object ExecuteScalar(DbCommand cmd)
{
if (cmd.Connection == null)
{
cmd.Connection = _factory.CreateConnection();
}
bool isClosed = cmd.Connection.State == ConnectionState.Closed;
try
{
if (isClosed)
{
cmd.Connection.Open();
}
return cmd.ExecuteScalar();
}
finally
{
if (isClosed)
{
cmd.Connection.Close();
}
}
} protected DbDataReader ExecuteReader(DbCommand cmd)
{
if (cmd.Connection == null)
{
cmd.Connection = _factory.CreateConnection();
}
bool isClosed = cmd.Connection.State == ConnectionState.Closed;
if (isClosed)
{
cmd.Connection.Open();
}
return cmd.ExecuteReader(isClosed ? CommandBehavior.CloseConnection : CommandBehavior.Default);
} protected DataTable ExecuteDataTable(DbCommand cmd, int startRecord = -, int maxRecords = )
{
var dt = new DataTable(DataTableName);
if (cmd.Connection == null)
{
cmd.Connection = _factory.CreateConnection();
}
using (DbDataAdapter da = _factory.CreateDataAdapter(cmd))
{
if (startRecord == -)
{
da.Fill(dt);
}
else
{
da.Fill(startRecord, maxRecords, dt);
}
}
return dt;
} protected DataSet ExecuteDataSet(DbCommand cmd)
{
var ds = new DataSet();
if (cmd.Connection == null)
{
cmd.Connection = _factory.CreateConnection();
}
using (DbDataAdapter da = _factory.CreateDataAdapter(cmd))
{
da.Fill(ds, DataTableName);
}
return ds;
}
#endregion #region Methods
/// <summary>
/// 使用调用方法最为映射方法来获取DataReader
/// </summary>
/// <param name="db"></param>
/// <param name="paramValues">按SQL语句中定义的Format顺序,对应传递参数值</param>
/// <returns>DataReader</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public int MappedExecNonQuery(params object[] paramValues)
{
var stack = new StackTrace();
MethodBase method = stack.GetFrame().GetMethod();
string sql = Config.GetSQL(method);
return this.ExecuteNonQuery(sql, paramValues);
}
public int ExecuteNonQuery(string formatSql, params object[] paramValues)
{
string text = DbUtility.GetFormat(formatSql, paramValues);
var cmd = this.PrepareCommand(text, CommandType.Text);
return this.ExecuteNonQuery(cmd);
} /// <summary>
/// 使用调用方法最为映射方法来获取DataReader
/// </summary>
/// <param name="db"></param>
/// <param name="paramValues">按SQL语句中定义的Format顺序,对应传递参数值</param>
/// <returns>DataReader</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public T ExecuteScalar<T>(params object[] paramValues)
{
var stack = new StackTrace();
MethodBase method = stack.GetFrame().GetMethod();
string sql = Config.GetSQL(method);
return this.ExecuteScalar<T>(sql, paramValues);
}
public T ExecuteScalar<T>(string formatSql, params object[] paramValues)
{
string text = DbUtility.GetFormat(formatSql, paramValues);
var cmd = this.PrepareCommand(text, CommandType.Text);
return (T)Convert.ChangeType(this.ExecuteScalar(cmd), typeof(T));
} /// <summary>
/// 使用调用方法最为映射方法来获取DataReader
/// </summary>
/// <param name="db"></param>
/// <param name="paramValues">按SQL语句中定义的Format顺序,对应传递参数值</param>
/// <returns>DataReader</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public DbDataReader MappedExecReader(params object[] paramValues)
{
var stack = new StackTrace();
MethodBase method = stack.GetFrame().GetMethod();
string sql = Config.GetSQL(method);
return this.ExecuteReader(sql, paramValues);
}
public DbDataReader ExecuteReader(string formatSql, params object[] paramValues)
{
string text = DbUtility.GetFormat(formatSql, paramValues);
var cmd = this.PrepareCommand(text, CommandType.Text);
return this.ExecuteReader(cmd);
} public DataTable ExecuteDataTable(string formatSql, params object[] paramValues)
{
return this.ExecuteDataTable(-, , formatSql, paramValues);
}
public DataTable ExecuteDataTable(int startRecord, int maxRecords, string formatSql, params object[] paramValues)
{
string text = DbUtility.GetFormat(formatSql, paramValues);
var cmd = this.PrepareCommand(text, CommandType.Text);
return this.ExecuteDataTable(cmd, startRecord, maxRecords);
} public int UpdateDataTable(DataTable dt, params string[] joinSelectSql)
{
int affected = ;
var cmd = this.PrepareCommand(string.Empty, CommandType.Text);
using (var da = this.Factory.CreateDataAdapter(cmd))
using (var cb = this.Factory.CreateCommandBuilder(da))
{
da.AcceptChangesDuringUpdate = false;
affected = da.Update(dt);
if (!joinSelectSql.IsNullOrEmpty())
{
for (int i = ; i < joinSelectSql.Length; i++)
{
cb.RefreshSchema();
da.SelectCommand.CommandText = joinSelectSql[i];
affected += da.Update(dt);
}
}
dt.AcceptChanges();
}
return affected;
}
#endregion #region StoredProc
#region Command
/// <summary>
/// cmd.CommandType = CommandType.StoredProcedure;
/// Always discoveredParameters[0].ParameterName == Database.ReturnParameterName
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
protected DbParameter[] GetDeriveParameters(DbCommand cmd)
{
string spName = cmd.CommandText;
DbParameter[] discoveredParameters = (DbParameter[])Cache[spName];
if (discoveredParameters == null)
{
string qualifiedName = cmd.GetType().AssemblyQualifiedName;
Type builderType = Type.GetType(qualifiedName.Insert(qualifiedName.IndexOf(','), "Builder"));
MethodInfo method = builderType.GetMethod("DeriveParameters", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod);
if (method == null)
{
throw new ArgumentException("The specified provider factory doesn't support stored procedures.");
}
if (cmd.Connection == null)
{
cmd.Connection = _factory.CreateConnection();
}
bool isClosed = cmd.Connection.State == ConnectionState.Closed;
try
{
if (isClosed)
{
cmd.Connection.Open();
}
method.Invoke(null, new object[] { cmd });
}
finally
{
if (isClosed)
{
cmd.Connection.Close();
}
}
Cache[spName] = discoveredParameters = new DbParameter[cmd.Parameters.Count];
cmd.Parameters.CopyTo(discoveredParameters, );
cmd.Parameters.Clear();
}
return discoveredParameters;
} public void DeriveParameters(DbCommand cmd)
{
DbParameter[] originalParameters = GetDeriveParameters(cmd);
for (int i = ; i < originalParameters.Length; i++)
{
cmd.Parameters.Add(((ICloneable)originalParameters[i]).Clone());
}
} public void DeriveAssignParameters(DbCommand cmd, object[] values)
{
DbParameter[] discoveredParameters = GetDeriveParameters(cmd);
if (cmd.Parameters.Count > || discoveredParameters.Length - != values.Length)
{
throw new ArgumentException("The number of parameters doesn't match number of values for stored procedures.");
}
cmd.Parameters.Add(((ICloneable)discoveredParameters[]).Clone());
for (int i = ; i < values.Length; )
{
object value = values[i] ?? DBNull.Value;
DbParameter discoveredParameter = discoveredParameters[++i];
object cloned = ((ICloneable)discoveredParameter).Clone();
((DbParameter)cloned).Value = value;
cmd.Parameters.Add(cloned);
}
} public void SetParameterValue(DbCommand cmd, int index, object value)
{
int startIndex = cmd.Parameters.Count > && cmd.Parameters[].ParameterName == ReturnParameterName ? : ;
cmd.Parameters[startIndex + index].Value = value;
}
public void SetParameterValue(DbCommand cmd, string name, object value)
{
cmd.Parameters[_factory.ParameterNamePrefix + name].Value = value;
} public object GetParameterValue(DbCommand cmd, int index)
{
int startIndex = cmd.Parameters.Count > && cmd.Parameters[].ParameterName == ReturnParameterName ? : ;
return cmd.Parameters[startIndex + index].Value;
}
public object GetParameterValue(DbCommand cmd, string name)
{
return cmd.Parameters[_factory.ParameterNamePrefix + name].Value;
} public object GetParameterReturnValue(DbCommand cmd)
{
if (cmd.Parameters.Count > && cmd.Parameters[].ParameterName == ReturnParameterName)
{
return cmd.Parameters[].Value;
}
return null;
}
#endregion #region Execute
protected virtual void FillOutputValue(DbCommand cmd, object[] values)
{
for (int i = ; i < cmd.Parameters.Count; i++)
{
var param = cmd.Parameters[i];
if (param.Direction == ParameterDirection.Output || param.Direction == ParameterDirection.InputOutput)
{
values[i - ] = param.Value;
}
}
} public int ExecuteStoredProcNonQuery(string spName, params object[] values)
{
var cmd = this.PrepareCommand(spName, CommandType.StoredProcedure);
DeriveAssignParameters(cmd, values);
FillOutputValue(cmd, values);
return ExecuteNonQuery(cmd);
} public object ExecuteStoredProcScalar(string spName, params object[] values)
{
var cmd = this.PrepareCommand(spName, CommandType.StoredProcedure);
DeriveAssignParameters(cmd, values);
FillOutputValue(cmd, values);
return ExecuteScalar(cmd);
} public DbDataReader ExecuteStoredProcReader(string spName, params object[] values)
{
var cmd = this.PrepareCommand(spName, CommandType.StoredProcedure);
DeriveAssignParameters(cmd, values);
FillOutputValue(cmd, values);
return ExecuteReader(cmd);
} public DataTable ExecuteStoredProcDataTable(string spName, params object[] values)
{
var cmd = this.PrepareCommand(spName, CommandType.StoredProcedure);
DeriveAssignParameters(cmd, values);
FillOutputValue(cmd, values);
return ExecuteDataTable(cmd);
} public DataSet ExecuteStoredProcDataSet(string spName, params object[] values)
{
var cmd = this.PrepareCommand(spName, CommandType.StoredProcedure);
DeriveAssignParameters(cmd, values);
FillOutputValue(cmd, values);
return ExecuteDataSet(cmd);
}
#endregion
#endregion
}
}

C# 调用配置文件SQL语句 真2B!的更多相关文章

  1. springmvc 项目完整示例04 整合mybatis mybatis所需要的jar包 mybatis配置文件 sql语句 mybatis应用

    百度百科: MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBat ...

  2. 第三节: EF调用普通SQL语句的两类封装(ExecuteSqlCommand和SqlQuery )

    一. 前言 在前面的两个章节中,我们分别详细介绍了EF的增删改的两种方式(方法和状态)和EF查询的两种方式( Lambda和Linq ),进行到这里,可以说对于EF,已经入门了,本来应该继续往下进行E ...

  3. ASP.NET MVC深入浅出(被替换) 第一节: 结合EF的本地缓存属性来介绍【EF增删改操作】的几种形式 第三节: EF调用普通SQL语句的两类封装(ExecuteSqlCommand和SqlQuery ) 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法 第六节: EF高级属性(二) 之延迟加载、立即加载、显示加载(含导航属性) 第十节: EF的三种追踪

    ASP.NET MVC深入浅出(被替换)   一. 谈情怀-ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态 ...

  4. mybatis执行test07测试类却显示test05测试类调用的sql语句出错

    1.测试类 @Test public void test07() { IStudentDao studentDao = new IStudentDaoImpl(); Student student = ...

  5. mybatis 的mapper配置文件sql语句中, 有时用到 大于, 小于等等

    一, 用<![CDATA[   ]]>标识,例如: <if test="create_timeStart != null and create_timeStart != ' ...

  6. 在项目中,多个方法会调用相同的sql语句,怎么解决各个方法的不同sql查询,解决冲突。

    公司的代码中sql语句,可能会被多个方法进行调用,但是有的方法会关联到别的表,这样的话,如果修改不当,那么同样调用该sql语句的方法,会出现报错. 最近做的公司的一个功能,就出现这样一个问题,虽然本功 ...

  7. Mybatis高级:Mybatis注解开发单表操作,Mybatis注解开发多表操作,构建sql语句,综合案例学生管理系统使用接口注解方式优化

    知识点梳理 课堂讲义 一.Mybatis注解开发单表操作 *** 1.1 MyBatis的常用注解 之前我们在Mapper映射文件中编写的sql语句已经各种配置,其实是比较麻烦的 而这几年来注解开发越 ...

  8. 为什么数据库有时候不能定位阻塞(Blocker)源头的SQL语句

    在SQL Server数据库或OACLE数据库当中,通常一个会话持有某个资源的锁,而另一个会话在请求这个资源,就会出现阻塞(blocking).这是DBA经常会遇到的情况.当出现SQL语句的阻塞时,很 ...

  9. IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题

    IT咨询顾问:一次吐血的项目救火   年后的一个合作公司上线了一个子业务系统,对接公司内部的单点系统.我收到该公司的技术咨询:项目启动后没有规律的突然无法登录了,重新启动后,登录一断时间后又无法重新登 ...

随机推荐

  1. ResponseUtil反射制造唯一结果

    调用:通过反射调用同一个类型的返回值 return fillResponse(response,Constants.SUCCESS,"获取数据成功","taskList& ...

  2. 慎用GetOpenFileName

    这两天发现了一个小问题,经过一上午的排查终于找到了问题的原因--Windows 7的API函数GetOpenFileName竟然有BUG! 请参考下面的MFC代码: CFileDialog dlg(T ...

  3. css读书笔记2:css工作原理

    css就是一种先选择html元素,然后设定选中元素css属性的机制.css选择符合要应用的样式构成一条css规则. 为文档添加样式的3种方法: 1.行内样式,直接写在特定标签的style属性中:2.嵌 ...

  4. DI 之 3.4 Bean的作用域(捌)

    3.4  Bean的作用域 什么是作用域呢?即"scope",在面向对象程序设计中一般指对象或变量之间的可见范围.而在Spring容器中是指其创建的Bean对象相对于其他Bean对 ...

  5. 3.3 使用Code First数据库迁移

    当Entity Framework Code First的数据模型发生异动时,默认会引发一个System.InvalidOpertaionException异常.一种解决方法是在Global.asax ...

  6. 30-Razor语法基础

    以往开发ASP.NET Web Form时,在ASPX页面上都会出现许多夹杂C#/VB.NET与HTML的情况,而先前使用<%...%>这种传统圆角括号的表示法会让HTML标签与ASP.N ...

  7. informix数据库下导出表结构

    1)导出数据库中所有的表结构到文件db.sql  $>dbschema -d your_database -t all  db.sql 2)导出数据库中所有的存储过程到文件db.sql  $&g ...

  8. centos7 学习

    1.centos pid文件: 在Linux系统的目录/var/run下面一般我们都会看到很多的*.pid文件.而且往往新安装的程序在运行后也会在/var/run目录下面产生自己的pid文件.那么这些 ...

  9. 张艾迪(创始人):出现在世界224C之前的这些时间

    出现在世界224C之前的这些时间 坐在大巴车上.用手塞住耳朵.繁杂的大巴车上.总会听见不喜欢听的声音.那时只有22.23岁的我.就像发明一些东西把所有不喜欢的声音都屏蔽掉.就像防火墙一样.那时候拥抱所 ...

  10. tableviewcell边距和设置值不符

    解决方法: 将Table View Cell的Layout Margins由Default改为Explicit,然后修改上下左右的边距.