/*********************************************************************************
** 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. java 多线程4(死锁)

    死锁现象: 死锁原因: 1.存在两个或两个以上的线程. 2.存在两个或两个或两个以上的共享资源. 死锁现象解决的方案: 没有方案只能尽量避免.

  2. webstorm激活码

    2016.2.3版本 43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0I0QTczWVlKIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZW ...

  3. [JavaScript] 函数同名问题

    存在同名函数时,最后的函数会覆盖掉以前的同名函数. var x = 1, y = z = 0; function add(n) { return n = n + 1; } y = add(x); fu ...

  4. 关于WorkFlow的使用以及例子

    近期做项目,项目需要用到工作流方面的技术,我在这里与大家分享一个workFlow学习的地址,共大家学习. http://www.cnblogs.com/foundation/ 各文档的说明: F资料├ ...

  5. mysql查询优化(持续更新中)

    1.        索引不会包含有NULL值的列 (1)   应尽量避免在where子句中对字段进行null值判断,否则将导致引擎放弃使用索引而进行全表扫描 (2)   数据库设计时不要让字段的默认值 ...

  6. Qt之QRadioButton

    简述 QRadioButton部件提供了一个带有文本标签的单选框(单选按钮). QRadioButton是一个可以切换选中(checked)或未选中(unchecked)状态的选项按钮.单选框通常呈现 ...

  7. swf2pdf转swf时字符集问题【转】

    今天转了一个的pdf是出现字符集问题,并转换的swf为乱码.出现的错误如下. 错误的原因是缺少中文字符集GBK-EUC-H.解决方法使用xpdf增加缺少的字符集.解决步骤如下: (一) 下载相关的xp ...

  8. MyEclipse自动补全与快捷键设置

    一般默认情况下,Eclipse ,MyEclipse的代码提示功能是比Microsoft Visual Studio的差很多的,主要是Eclipse ,MyEclipse本身有很多选项是默认关闭的,要 ...

  9. IKAnalyzer进行中文分词和去停用词

    最近学习主题模型pLSA.LDA,就想拿来试试中文.首先就是找文本进行切词.去停用词等预处理,这里我找了开源工具IKAnalyzer2012,下载地址:(:(注意:这里尽量下载最新版本,我这里用的IK ...

  10. JButton按钮

    1.方法 void  setSize(width,height):设置按钮大小 void  setBounds(x,y,width,heigth):设置按钮的左上角顶点位置和大小 void  setC ...