首页 » .NET » 自己动手写ORM框架(二)-AdoHelper支持多数据库操作的封装(1)

自己动手写ORM框架(二)-AdoHelper支持多数据库操作的封装(1)

原文 http://blog.csdn.net/coolhe21cn/article/details/79075746

2018-01-17 02:00:33阅读(195)

主题:本节主要是底层的针对于数据库的CRUD,包括对于不同类型数据库的可扩展性。第一步:编写AdoHelper类,用于封装对数据库的操作,能同时支持多个数据库(目前支持SqlServer、Oracle、Access),可扩展支持任何类型的数据库。

app.config
<?xml version="1.0"?>
<configuration>
<appSettings>
    <add key="dbType" value="oracle"/>
    <add key="connectionString" value="DataSource=test;UserID=test;Password=123"/>
</appSettings>
<system.web>
    <compilation debug="true">
    </compilation>
    <authentication mode="Windows"/>
</system.web>
</configuration>
TypeUtils.cs
/// <summary>
/// 对象类型
/// </summary>
public class TypeUtils
{
    public static object ConvertForType(object value, Type type)
    {
        switch (type.FullName)
        {
            case "System.String":
                value = value.ToString();
                break;
            case "System.Boolean":
                value = bool.Parse(value.ToString());
                break;
            case "System.Int16":
            case "System.Int32":
            case "System.Int64":
                value = int.Parse(value.ToString());
                break;
            case "System.Double":
                value = double.Parse(value.ToString());
                break;
            case "System.Decimal":
                value = new decimal(double.Parse(value.ToString()));
                break;
        }
        return value;
    }
}
CommonUtils.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Reflection;
namespace System.ORM.Common
{
    public class CommonUtils
    {
        /// <summary>  
        /// 用于字符串和枚举类型的转换
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="value"></param> 
        /// <returns></returns>
        public static T EnumParse<T>(string value)
        {
            try
            {
                return (T)Enum.Parse(typeof(T), value);
            }
            catch
            {
                throw new Exception("传入的值与枚举值不匹配。");
            }
        }
        /// <summary>  
        /// 根据传入的Key获取配置文件中的Value值
        /// </summary>
        /// <param name="Key"></param>  
        /// <returns></returns> 
        public static string GetConfigValueByKey(string Key)
        {
            try
            {
                return ConfigurationManager.AppSettings[Key].ToString();
            }
            catch
            {
                throw new Exception("web.config中 Key=\"" + Key + "\"未配置或配置错误!");
            }
        }
        /// <summary>
        /// 判断对象空值或者Null值
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Boolean IsNullOrEmpty(Object value)
        {
            if (value == null)
                return true;
            if (String.IsNullOrEmpty(value.ToString()))
                return true;
            return false;
        }
    }
}
DbFactory.cs
/// <summary>
/// 数据库工厂类
/// </summary>
public class DbFactory
{
    /// <summary>  
    /// 根据配置文件中所配置的数据库类型
    /// 来获取命令参数中的参数符号oracle为":",sqlserver为"@"  
    /// </summary>  
    /// <returns></returns>  
    public static string CreateDbParmCharacter()
    {
        string character = string.Empty;
        switch (AdoHelper.DbType)
        {
            case DbProvider.SQLSERVER:
                character = "@";
                break;
            case DbProvider.ORACLE:
                character = ":";
                break;
            case DbProvider.ACCESS:
                character = "@";
                break;
            default:
                throw new Exception("数据库类型目前不支持!");
        }
        return character;
    }
    /// <summary>  
    /// 根据配置文件中所配置的数据库类型和传入的  
    /// 数据库链接字符串来创建相应数据库连接对象 
    /// </summary>  
    /// <param name="connectionString"></param>  
    /// <returns></returns>  
    public static IDbConnection CreateDbConnection(string connectionString)
    {
        IDbConnection conn = null;
        switch (AdoHelper.DbType)
        {
            case DbProvider.SQLSERVER:
                conn = new SqlConnection(connectionString);
                break;
            case DbProvider.ORACLE:
                conn = new OracleConnection(connectionString);
                break;
            case DbProvider.ACCESS:
                conn = new OleDbConnection(connectionString);
                break;
            default:
                throw new Exception("数据库类型目前不支持!");
        }
        return conn;
    }
    /// 根据配置文件中所配置的数据库类型  
    /// 来创建相应数据库命令对象  
    /// </summary>  
    /// <returns></returns>  
    public static IDbCommand CreateDbCommand()
    {
        IDbCommand cmd = null;
        switch (AdoHelper.DbType)
        {
            case DbProvider.SQLSERVER:
                cmd = new SqlCommand();
                break;
            case DbProvider.ORACLE:
                cmd = new OracleCommand();
                break;
            case DbProvider.ACCESS:
                cmd = new OleDbCommand();
                break;
            default:
                throw new Exception("数据库类型目前不支持!");
        }
        return cmd;
    }
    /// <summary>  
    /// 根据配置文件中所配置的数据库类型  
    /// 来创建相应数据库适配器对象  
    /// </summary>  
    /// <returns></returns>  
    public static IDbDataAdapter CreateDataAdapter()
    {
        IDbDataAdapter adapter = null;
        switch (AdoHelper.DbType)
        {
            case DbProvider.SQLSERVER:
                adapter = new SqlDataAdapter();
                break;
            case DbProvider.ORACLE:
                adapter = new OracleDataAdapter();
                break;
            case DbProvider.ACCESS:
                adapter = new OleDbDataAdapter();
                break;
            default:
                throw new Exception("数据库类型目前不支持!");
        }
        return adapter;
    }
    /// <summary>  
    /// 根据配置文件中所配置的数据库类型  
    /// 和传入的命令对象来创建相应数据库适配器对象  
    /// </summary>  
    /// <returns></returns>  
    public static IDbDataAdapter CreateDataAdapter(IDbCommand cmd)
    {
        IDbDataAdapter adapter = null;
        switch (AdoHelper.DbType)
        {
            case DbProvider.SQLSERVER:
                adapter = new SqlDataAdapter((SqlCommand)cmd);
                break;
            case DbProvider.ORACLE:
                adapter = new OracleDataAdapter((OracleCommand)cmd);
                break;
            case DbProvider.ACCESS:
                adapter = new OleDbDataAdapter((OleDbCommand)cmd);
                break;
            default: throw new Exception("数据库类型目前不支持!");
        }
        return adapter;
    }
    /// <summary>  
    /// 根据配置文件中所配置的数据库类型  
    /// 来创建相应数据库的参数对象  
    /// </summary>  
    /// <returns></returns>  
    public static IDbDataParameter CreateDbParameter()
    {
        IDbDataParameter param = null;
        switch (AdoHelper.DbType)
        {
            case DbProvider.SQLSERVER:
                param = new SqlParameter();
                break;
            case DbProvider.ORACLE:
                param = new OracleParameter();
                break;
            case DbProvider.ACCESS:
                param = new OleDbParameter();
                break;
            default:
                throw new Exception("数据库类型目前不支持!");
        }
        return param;
    }
    /// <summary>  
    /// 根据配置文件中所配置的数据库类型  
    /// 和传入的参数来创建相应数据库的参数数组对象  
    /// </summary>  
    /// <returns></returns>  
    public static IDbDataParameter[] CreateDbParameters(int size)
    {
        int i = 0;
        IDbDataParameter[] param = null;
        switch (AdoHelper.DbType)
        {
            case DbProvider.SQLSERVER:
                param = new SqlParameter[size];
                while (i < size) { param[i] = new SqlParameter(); i++; }
                break;
            case DbProvider.ORACLE:
                param = new OracleParameter[size];
                while (i < size) { param[i] = new OracleParameter(); i++; }
                break;
            case DbProvider.ACCESS:
                param = new OleDbParameter[size];
                while (i < size) { param[i] = new OleDbParameter(); i++; }
                break;
            default:
                throw new Exception("数据库类型目前不支持!");
        }
        return param;
    }
    /// <summary>  
    /// 根据配置文件中所配置的数据库类型  
    /// 来创建相应数据库的事物对象  
    /// </summary>  
    /// <returns></returns>  
    public static IDbTransaction CreateDbTransaction()
    {
        IDbConnection conn = CreateDbConnection(AdoHelper.ConnectionString);
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        return conn.BeginTransaction();
    }
}  
AdoHelper.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Rizi.Frame.Orm.Common;
namespace Rizi.Frame.Orm.DBUtility
{
    public class AdoHelper 
    {
        //获取数据库类型
        private static string strDbType = CommonUtils.GetConfigValueByKey("dbType").ToUpper();
        //将数据库类型转换成枚举类型  
        public static DbProvider DbType = DbProviderEnumParse<DbProvider>(strDbType);
         //获取数据库连接字符串  
        public static string ConnectionString = GetConnectionString("connectionString");
        public static string DbParmChar = DbFactory.CreateDbParmCharacter();
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); 
        /// <summary>  
        ///通过提供的参数,执行无结果集的数据库操作命令  
        /// 并返回执行数据库操作所影响的行数。  
        /// </summary>  
        /// <param name="connectionString">数据库连接字符串</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param> 
        /// <param name="commandText">存储过程名称或者T-SQL命令行<</param>  
        /// <param name="commandParameters">执行命令所需的参数数组</param>  
        /// <returns>返回通过执行命令所影响的行数</returns>  
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params IDbDataParameter[] commandParameters)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            using (IDbConnection conn = DbFactory.CreateDbConnection(connectionString))  
            {  
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);  
                int val = cmd.ExecuteNonQuery();  
                cmd.Parameters.Clear();  
                return val;  
            }  
        }  
        /// <summary>  
        ///通过提供的参数,执行无结果集的数据库操作命令  
        /// 并返回执行数据库操作所影响的行数。  
        /// </summary>  
        /// <param name="connectionString">数据库连接字符串</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行<</param>  
        /// <returns>返回通过执行命令所影响的行数</returns>  
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            using (IDbConnection conn = DbFactory.CreateDbConnection(connectionString))  
            {  
                PrepareCommand(cmd, conn, null, cmdType, cmdText, null);  
                int val = cmd.ExecuteNonQuery();  
                cmd.Parameters.Clear();  
                return val;  
            }  
        }  
        /// <summary>  
        ///通过提供的参数,执行无结果集返回的数据库操作命令  
        ///并返回执行数据库操作所影响的行数。  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="conn">数据库连接对象</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行</param>  
        /// <param name="commandParameters">执行命令所需的参数数组</param>  
        /// <returns>返回通过执行命令所影响的行数</returns>  
        public static int ExecuteNonQuery(IDbConnection connection, CommandType cmdType, string cmdText, params IDbDataParameter[] commandParameters)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);  
            int val = cmd.ExecuteNonQuery();  
            cmd.Parameters.Clear();  
            return val;  
        }  
        /// <summary>  
        ///通过提供的参数,执行无结果集返回的数据库操作命令  
        ///并返回执行数据库操作所影响的行数。  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="conn">数据库连接对象</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行</param>  
        /// <returns>返回通过执行命令所影响的行数</returns>  
        public static int ExecuteNonQuery(IDbConnection connection, CommandType cmdType, string cmdText)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            PrepareCommand(cmd, connection, null, cmdType, cmdText, null);  
            int val = cmd.ExecuteNonQuery();  
            cmd.Parameters.Clear();  
            return val;  
        }  
        /// <summary>  
        ///通过提供的参数,执行无结果集返回的数据库操作命令  
        ///并返回执行数据库操作所影响的行数。  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="trans">sql事务对象</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行<</param>  
        /// <param name="commandParameters">执行命令所需的参数数组</param>  
        /// <returns>返回通过执行命令所影响的行数</returns>  
        public static int ExecuteNonQuery(IDbTransaction trans, CommandType cmdType, string cmdText, params IDbDataParameter[] commandParameters)  
        {  
            IDbConnection conn = null;  
            if (trans == null)  
            {  
                conn = DbFactory.CreateDbConnection(ConnectionString);  
            }  
            else   
            {  
                conn = trans.Connection;  
            }  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            PrepareCommand(cmd, conn, trans, cmdType, cmdText, commandParameters);  
            int val = cmd.ExecuteNonQuery();  
            cmd.Parameters.Clear();  
            return val;  
        }  
        /// <summary>  
        ///通过提供的参数,执行无结果集返回的数据库操作命令  
        ///并返回执行数据库操作所影响的行数。  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="trans">sql事务对象</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行<</param>  
        /// <returns>返回通过执行命令所影响的行数</returns>  
        public static int ExecuteNonQuery(IDbTransaction trans, CommandType cmdType, string cmdText)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, null);  
            int val = cmd.ExecuteNonQuery();  
            cmd.Parameters.Clear();  
            return val;  
        }  
        /// <summary>  
        /// 使用提供的参数,执行有结果集返回的数据库操作命令  
        /// 并返回SqlDataReader对象  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="connectionString">数据库连接字符串</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行<</param>  
        /// <param name="commandParameters">执行命令所需的参数数组</param>  
        /// <returns>返回SqlDataReader对象</returns>  
        public static IDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params IDbDataParameter[] commandParameters)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            IDbConnection conn = DbFactory.CreateDbConnection(connectionString);  
            //我们在这里使用一个 try/catch,因为如果PrepareCommand方法抛出一个异常,我们想在捕获代码里面关闭  
            //connection连接对象,因为异常发生datareader将不会存在,所以commandBehaviour.CloseConnection  
            //将不会执行。  
            try  
            {  
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);  
                IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);  
                cmd.Parameters.Clear();  
                return rdr;  
            }  
            catch  
            {  
                conn.Close();  
                throw;  
            }  
        }  
        /// <summary>  
        ///使用提供的参数,执行有结果集返回的数据库操作命令  
        /// 并返回SqlDataReader对象  
        /// </summary>  
        /// <param name="connectionString">数据库连接字符串</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行<</param>  
        /// <returns>返回SqlDataReader对象</returns>  
        public static IDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            IDbConnection conn = DbFactory.CreateDbConnection(connectionString);  
            //我们在这里使用一个 try/catch,因为如果PrepareCommand方法抛出一个异常,我们想在捕获代码里面关闭  
            //connection连接对象,因为异常发生datareader将不会存在,所以commandBehaviour.CloseConnection  
            //将不会执行。  
            try  
            {  
                PrepareCommand(cmd, conn, null, cmdType, cmdText, null);  
                IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);  
                cmd.Parameters.Clear();  
                return rdr;  
            }  
            catch  
            {  
                conn.Close();  
                throw;  
            }  
        }  
        /// <summary>  
        /// 查询数据填充到数据集DataSet中  
        /// </summary>  
        /// <param name="connectionString">数据库连接字符串</param>  
        /// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="cmdText">命令文本</param>  
        /// <param name="commandParameters">参数数组</param>  
        /// <returns>数据集DataSet对象</returns>  
        public static DataSet dataSet(string connectionString, CommandType cmdType, string cmdText, params IDbDataParameter[] commandParameters)  
        {  
            DataSet ds = new DataSet();  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            IDbConnection conn = DbFactory.CreateDbConnection(connectionString);  
            try  
            {  
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);  
                IDbDataAdapter sda = DbFactory.CreateDataAdapter(cmd);  
                sda.Fill(ds);  
                return ds;  
            }  
            catch  
            {  
                conn.Close();  
                throw;  
            }  
            finally  
            {  
                conn.Close();  
                cmd.Dispose();  
            }  
        }  
        /// <summary>  
        /// 查询数据填充到数据集DataSet中  
        /// </summary>  
        /// <param name="connectionString">数据库连接字符串</param>  
        /// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="cmdText">命令文本</param>  
        /// <returns>数据集DataSet对象</returns>  
        public static DataSet dataSet(string connectionString, CommandType cmdType, string cmdText)  
        {  
            DataSet ds = new DataSet();  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            IDbConnection conn = DbFactory.CreateDbConnection(connectionString);  
            try  
            {  
                PrepareCommand(cmd, conn, null, cmdType, cmdText, null);  
                IDbDataAdapter sda = DbFactory.CreateDataAdapter(cmd);  
                sda.Fill(ds);  
                return ds;  
            }  
            catch  
            {  
                conn.Close();  
                throw;  
            }  
            finally  
            {  
                conn.Close();  
                cmd.Dispose();  
            }  
        }  
        /// <summary>  
        /// 依靠数据库连接字符串connectionString,  
        /// 使用所提供参数,执行返回首行首列命令  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="connectionString">数据库连接字符串</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行</param>  
        /// <param name="commandParameters">执行命令所需的参数数组</param>  
        /// <returns>返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。</returns>  
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params IDbDataParameter[] commandParameters)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            using (IDbConnection connection = DbFactory.CreateDbConnection(connectionString))  
            {  
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);  
                object val = cmd.ExecuteScalar();  
                cmd.Parameters.Clear();  
                return val;  
            }  
        }  
        /// <summary>  
        /// 依靠数据库连接字符串connectionString,  
        /// 使用所提供参数,执行返回首行首列命令  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="connectionString">数据库连接字符串</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行</param>  
        /// <returns>返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。</returns>  
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            using (IDbConnection connection = DbFactory.CreateDbConnection(connectionString))  
            {  
                PrepareCommand(cmd, connection, null, cmdType, cmdText, null);  
                object val = cmd.ExecuteScalar();  
                cmd.Parameters.Clear();  
                return val;  
            }  
        }  
        /// <summary>  
        ///依靠数据库连接字符串connectionString,  
        /// 使用所提供参数,执行返回首行首列命令  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="conn">数据库连接对象</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行</param>  
        /// <param name="commandParameters">执行命令所需的参数数组</param>  
        /// <returns>返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。</returns>  
        public static object ExecuteScalar(IDbConnection connection, CommandType cmdType, string cmdText, params IDbDataParameter[] commandParameters)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);  
            object val = cmd.ExecuteScalar();  
            cmd.Parameters.Clear();  
            return val;  
        }  
        /// <summary>  
        ///依靠数据库连接字符串connectionString,  
        /// 使用所提供参数,执行返回首行首列命令  
        /// </summary>  
        /// <remarks>  
        /// e.g.:    
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));  
        /// </remarks>  
        /// <param name="conn">数据库连接对象</param>  
        /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="commandText">存储过程名称或者T-SQL命令行</param>  
        /// <param name="commandParameters">执行命令所需的参数数组</param>  
        /// <returns>返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。</returns>  
        public static object ExecuteScalar(IDbConnection connection, CommandType cmdType, string cmdText)  
        {  
            IDbCommand cmd = DbFactory.CreateDbCommand();  
            PrepareCommand(cmd, connection, null, cmdType, cmdText, null);  
            object val = cmd.ExecuteScalar();  
            cmd.Parameters.Clear();  
            return val;  
        }  
        /// <summary>  
        /// add parameter array to the cache  
        /// </summary>  
        /// <param name="cacheKey">Key to the parameter cache</param>  
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>  
        public static void CacheParameters(string cacheKey, params IDbDataParameter[] commandParameters)  
        {  
            parmCache[cacheKey] = commandParameters;  
        }  
        /// <summary>  
        /// 查询缓存参数  
        /// </summary>  
        /// <param name="cacheKey">使用缓存名称查找值</param>  
        /// <returns>缓存参数数组</returns>  
        public static IDbDataParameter[] GetCachedParameters(string cacheKey)  
        {  
            IDbDataParameter[] cachedParms = (IDbDataParameter[])parmCache[cacheKey];  
            if (cachedParms == null)  
                return null;  
            IDbDataParameter[] clonedParms = new IDbDataParameter[cachedParms.Length];  
            for (int i = 0, j = cachedParms.Length; i < j; i++)  
                clonedParms[i] = (IDbDataParameter)((ICloneable)cachedParms[i]).Clone();  
            return clonedParms;  
        }  
        /// <summary>  
        /// 为即将执行准备一个命令  
        /// </summary>  
        /// <param name="cmd">SqlCommand对象</param>  
        /// <param name="conn">SqlConnection对象</param>  
        /// <param name="trans">IDbTransaction对象</param>  
        /// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>  
        /// <param name="cmdText">存储过程名称或者T-SQL命令行, e.g. Select * from Products</param>  
        /// <param name="cmdParms">SqlParameters to use in the command</param>  
        private static void PrepareCommand(IDbCommand cmd, IDbConnection conn, IDbTransaction trans, CommandType cmdType, string cmdText, IDbDataParameter[] cmdParms)  
        {  
            if (conn.State != ConnectionState.Open)  
                conn.Open();  
            cmd.Connection = conn;  
            cmd.CommandText = cmdText;  
            if (trans != null)  
                cmd.Transaction = trans;  
            cmd.CommandType = cmdType;  
            if (cmdParms != null)  
            {  
                foreach (IDbDataParameter parm in cmdParms)  
                    cmd.Parameters.Add(parm);  
            }  
        }  
        /// <summary>  
        /// 根据传入的Key获取配置文件中  
        /// 相应Key的数据库连接字符串  
        /// </summary>  
        /// <param name="Key"></param>  
        /// <returns></returns>  
        public static string GetConnectionString(string Key)  
        {  
            try  
            {  
                return CommonUtils.GetConfigValueByKey(Key);  
            }  
            catch  
            {  
                throw new Exception("web.config文件appSettings中数据库连接字符串未配置或配置错误,必须为Key=\"connectionString\"");  
            }  
        }        
        /// <summary>  
        /// 用于数据库类型的字符串枚举转换  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="value"></param> 
        /// <returns></returns>  
        public static T DbProviderEnumParse<T>(string value)  
        {  
            try  
            {  
                return CommonUtils.EnumParse<T>(value);  
            }  
            catch  
            {  
                throw new Exception("数据库类型\"" + value + "\"错误,请检查!");  
            }  
        } 
    }  
}

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹