/*********************************************************************************
** 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. 【转】PackageInfo、ResolveInfo 笔记

    1.PackageInfo.ResolveInfo PackageItemInfo:包含了一些信息的基类, 它的直接子类有: ApplicationInfo. ComponentInfo.Instru ...

  2. WEB网页插件 如何实现 选择上传图片路径 【高级问题】

    发表于 2010-10-22 12:11 | |只看楼主       按键精灵程序里面的WEB网页插件 如何实现 选择上传图片路径 我想在上传图片的选框设置图片路径为 C:\fakepath\001. ...

  3. mysql+tomcat+spring 配置心得(从0开始搭环境)

    前几天公司竞一个标要做个POC,前端AugularJs做mobile界面,后端Spring MVC做Restful API供前端调用. 时间紧急,大家都忙,so我这个不写代码的闲人花一上午配了一套Sp ...

  4. 1到N中1出现的次数

    这个问题关键在于好好分析一些样例如: 给定123这个数,你说这个从1到123所有数字中,1出现的次数是多少? 首先我们要分析个位上1出现的次数,我们看看什么情况下个位出现1: 1,11,21,31,4 ...

  5. iOS 使用Keychain 保存 用户名和密码到 本地

    iOS 使用Keychain 保存 用户名和密码到 本地 之前曾把一些简单的数据保存在了plist,文件,及NsuserDefault里面, 但是如果要保存密码之类的,保存在本地就很不安全了: 但是利 ...

  6. JSON Viewer

    http://jsonviewer.codeplex.com/ jsoneditor https://github.com/josdejong/jsoneditor

  7. poj1190 生日蛋糕(深搜+剪枝)

    题目链接:poj1190 生日蛋糕 解题思路: 深搜,枚举:每一层可能的高度和半径 确定搜索范围:底层蛋糕的最大可能半径和最大可能高度 搜索顺序:从底层往上搭蛋糕,在同一层尝试时,半径和高度都是从大到 ...

  8. HTML5的 2D SVG和SVG DOM的学习笔记(1)

    (项目中要使用SVG,只好补充知识了) HTML体系中,最常用的绘制矢量图的技术是SVG和HTML5新增加的canvas元素.这两种技术都支持绘制矢量图和光栅图. 一.SVG概述 可缩放矢量图形(Sc ...

  9. Windows Store App 应用设置存储

    应用设置存储主要分为本地存储和漫游存储两种方式.本地存储是指将应用的设置信息存储在本地存储空间中,而漫游存储则是指将应用的设置信息存储在网络服务器中,相对于本地存储而言,漫游存储支持多台设备之间的应用 ...

  10. 简单管理用户SESSION小记(个人观点,欢迎斧正)

    做了几年码农,记录下一般涉及到用户session管理的方法. 问题说明: a.用户如果点击退出时,可以获取用户动作,这样可以销毁session. b.用户直接关闭浏览器或者直接意外关机情况,无法获取用 ...