using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.Configuration;
using System.Reflection;
using System.Xml;
namespace DBFactory
{
    /// <summary>
    /// DBOperator数据库操作对象
    /// 创建者：Richard.Liu
    /// </summary>
    public class DBOperator
    {
        #region 原创
        private IDictionary settings;
        private string _connstring;
        private DBFactory _dbf;
        private IDbConnection _dbconn;
        private IDbTransaction _dbtrans;
        private string _DBConnInfo;
        /// <summary>
        /// 数据库操作错误信息
        /// </summary>
        public string DBConnInfo
        {
            get { return _DBConnInfo; }
            //set { _DBConnInfo = value; }
        }
        /// <summary>
        /// 通过读取DBFactory.dll.config创建DBFactory的实例；
        /// 初始化数据库连接字符串ConnString
        /// </summary>
        public DBOperator()
        {
            try
            {
                settings = GetConfig();
                if (settings.Count < 1)
                {
                    _DBConnInfo = "数据库工厂的设置参数读取错误!";
                    return;
                }
                else
                {
                    _connstring = settings["ConnString"].ToString();
                    string classname = "DBFactory." + settings["DBFactory"];
                    this._dbf = (DBFactory)Assembly.Load("DBFactory").CreateInstance(classname);
                    Open();
                }
                
            }
            catch(Exception ex)
            {
                _DBConnInfo = ex.Message;
                throw ex;
                
            }
        }

        /// <summary>
        /// 通过读取DBFactory.dll.config创建DBFactory的实例；
        /// 初始化数据库连接字符串ConnString
        /// </summary>
        /// <param name="ConnString">数据库连接参数</param>
        public DBOperator(string ConnString)
        {
            try
            {
                settings = GetConfig();
                if (settings.Count < 1)
                {
                    _DBConnInfo = "数据库工厂的设置参数读取错误!";
                    return;
                }
                else
                {
                    _connstring = settings[ConnString].ToString();
                    string classname = "DBFactory." + settings["DBFactory"];
                    this._dbf = (DBFactory)Assembly.Load("DBFactory").CreateInstance(classname);
                    Open();
                }

            }
            catch (Exception ex)
            {
                _DBConnInfo = ex.Message;
                //throw ex;

            }
        }

        /// <summary>
        /// 通过读取DBFactory.dll.config创建DBFactory的实例；
        /// 初始化数据库连接字符串ConnString
        /// </summary>
        /// <param name="ConnString">数据库连接参数</param>
        /// <param name="DbFactory">数据库类工厂参数</param>
        public DBOperator(string ConnString, string DbFactory)
        {
            try
            {
                settings = GetConfig();
                if (settings.Count < 1)
                {
                    _DBConnInfo = "数据库工厂的设置参数读取错误!";
                    return;
                }
                else
                {
                    _connstring = settings[ConnString].ToString();
                    string classname = "DBFactory." + settings[DbFactory];
                    this._dbf = (DBFactory)Assembly.Load("DBFactory").CreateInstance(classname);
                    Open();
                }

            }
            catch (Exception ex)
            {
                _DBConnInfo = ex.Message;
                //throw ex;

            }
        }

        /// <summary>
        /// 默认传递值参false，代表不连接数据库，只是为了修改数据库连接配置
        /// </summary>
        /// <param name="ConnError"></param>
        public DBOperator(bool ConnError)
        {
            ConnError = false;
        }
        /// <summary>
        /// 获得配置文件路径和文件名
        /// </summary>
        /// <returns></returns>
        private string AppConfig()
        {
            Assembly asm = Assembly.GetCallingAssembly();
            string cfgFile = asm.Location + ".config";
            return cfgFile;
        }
        /// <summary>
        /// 获得指定项（Key）的值
        /// </summary>
        /// <param name="appKey"></param>
        /// <returns></returns>
        public  string GetValue(string appKey)
        {
            XmlDocument xDoc = new XmlDocument();
            try
            {
                xDoc.Load(AppConfig());
                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//appSettings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
                
                if (xElem != null)

                    return xElem.GetAttribute("value");
                else
                    return "";
            }
            catch (Exception)
            {
                return "";
            }
        }
        /// <summary>
        /// 设定指定项的值
        /// </summary>
        /// <param name="AppKey"></param>
        /// <param name="AppValue"></param>
        public  void SetValue(string AppKey, string AppValue)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(AppConfig());
                XmlNode xNode;
                XmlElement xElem1;
                XmlElement xElem2;
                xNode = xDoc.SelectSingleNode("//appSettings");
                xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
                if (xElem1 != null)
                {
                    xElem1.SetAttribute("value", AppValue);
                }
                else
                {
                    xElem2 = xDoc.CreateElement("add");
                    xElem2.SetAttribute("key", AppKey);
                    xElem2.SetAttribute("value", AppValue);
                    xNode.AppendChild(xElem2);
                }
                xDoc.Save(AppConfig());
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 通过读取XML文档获得DBFactory.dll.config的内容
        /// </summary>
        /// <returns>appSettings所有key的值</returns>
        private   IDictionary GetConfig()
        {
            // Open and parse configuration file for specified
            // assembly, returning collection to caller for future
            // use outside of this class.
            //
            try
            {
                Assembly asm= Assembly.GetCallingAssembly();
                
                string cfgFile = asm.Location + ".config";
                const string nodeName = "appSettings";

                XmlDocument doc = new XmlDocument();
                doc.Load(cfgFile);//20100726

                XmlNodeList nodes = doc.GetElementsByTagName(nodeName);

                foreach (XmlNode node in nodes)
                {
                    if (node.LocalName == nodeName)
                    {
                        DictionarySectionHandler handler = new DictionarySectionHandler();
                        return (IDictionary)handler.Create(null, null, node);
                    }
                }
            }
            catch(Exception ex)
            {
                throw(ex);
            }

            return (null);
        }
        /// <summary>
        /// 打开数据库联接
        /// </summary>
        /// <returns>ｔｒｕｅ代表连接成功</returns>
        public bool  Open()
        {
            try
            {
                
                _dbconn = _dbf.GetDBConnection();
                if (_dbconn.State == ConnectionState.Open)
                {
                    return true;
                }
                _dbconn.ConnectionString = _connstring;
                _dbconn.Open();
                
                return true;
            }
            catch (Exception ex)
            {
                _DBConnInfo = ex.Message;
                //throw ex;
                return false;
            }
            
        }
        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        public void Close()
        {
            try
            {
                if (_dbconn.State == ConnectionState.Open)
                {
                    _dbconn.Close();
                }
            }
            catch (Exception ex)
            {
                _DBConnInfo = ex.Message;
                throw ex;
                
            }
        }
        /// <summary>
        /// 数据库事务开始
        /// </summary>
        /// <param name="LockAction">指定连接的事务索行为</param>
        public void TransBegin(IsolationLevel LockAction)
        {
            try
            {
                Open();//20091218
                _dbtrans = _dbf.GetDBTransaction(LockAction);
            }
            catch (Exception ex)
            {
                Close();//20091218
                throw ex;
            }
        }
        /// <summary>
        /// 数据库事务开始；默认的连接的事务索行为IsolationLevel.ReadCommitted
        /// 在正在读取数据时保持共享锁
        /// </summary>
        public void TransBegin()
        {
            try
            {
                Open();//20091218
                _dbtrans = _dbf.GetDBTransaction(IsolationLevel.ReadCommitted);
            }
            catch (Exception ex)
            {
                Close();//20091218
                throw ex;
            }
        }
        /// <summary>
        /// 事务提交
        /// </summary>
        public void TransCommit()
        {
            try
            {
                _dbtrans.Commit();
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 事务回滚
        /// </summary>
        public void TransRollback()
        {
            try
            {
                _dbtrans.Rollback();
            }
            catch (Exception ex)
            { throw ex; }
        }
        /// <summary>
        /// 执行SQL语句，该命令最好在数据层应用；在业务逻辑层最好用模型类作为参数和返回值
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataSet ExceSQL(string sql)
        {//20100108
            DataSet ds;
            try
            {
                //20091218
                Open();
                IDbCommand dbc = _dbf.GetDBCommand();
                if (_dbtrans != null)
                {
                    dbc.Transaction = _dbtrans;
                }
                dbc.Connection = _dbconn;
                dbc.CommandText = sql;
                IDbDataAdapter ida = _dbf.GetDataAdapter(dbc);
                //20100108
                ds = new DataSet();
                ida.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                //20091218
                Close();
                _DBConnInfo = ex.Message;
                throw ex;
                //return null;
            }
            finally
            {//20100108
                ds = null;
            }

        }

        #endregion 

        #region 借用网络改型
        #region 公用方法

        public   int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        public int GetMaxID(string FieldName, string TableName, string ConditionFieldName, string ConditionValue)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName + " where " + ConditionFieldName + "=" + ConditionValue;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        public   bool Exists(string strSql)
        {
            object obj =GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public   bool Exists(string strSql, params IDbDataParameter[] cmdParms)
        {
            object obj =GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public   int ExecuteSql(string SQLString)
        {
           using (IDbCommand cmd = _dbf.GetDBCommand(SQLString, _dbconn))
                {
                    try
                    {
                        Open();//20091218
                        if (_dbtrans != null)
                        {
                            cmd.Transaction = _dbtrans;
                        }
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (Exception E)
                    {
                        Close();//20091218
                        throw E;
                    }
                }
            
        }

        /// <summary>
        /// 执行SQL语句，设置命令的执行等待时间
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="Times"></param>
        /// <returns></returns>
        public   int ExecuteSqlByTime(string SQLString, int Times)
        {
            using (IDbCommand cmd = _dbf.GetDBCommand(SQLString, _dbconn))
                {
                    try
                    {
                        Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (Exception E)
                    {
                        Close();
                        throw new Exception(E.Message);
                    }
                }
            
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public   void ExecuteSqlTran(ArrayList SQLStringList)
        {
            	Open();
                IDbCommand cmd = _dbf.GetDBCommand();//IDbCommand cmd = _dbf.GetDBCommand();
                cmd.Connection = _dbconn;
                TransBegin();
                cmd.Transaction = _dbtrans ;
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    TransCommit();
                }
                catch (Exception E)
                {
                    TransRollback();
                    throw new Exception(E.Message);
                }
            
        }
        /// <summary>
        /// 执行带一个存储过程参数的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public   int ExecuteSql(string SQLString, string content)
        {
            IDbCommand cmd = _dbf.GetDBCommand(SQLString, _dbconn);
                IDbDataParameter myParameter =_dbf.GetParameter("@content", DbType.String);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (Exception E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    Close();
                }
           
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public   object ExecuteSqlGet(string SQLString, string content)
        {
            IDbCommand cmd = _dbf.GetDBCommand(SQLString, _dbconn);
                IDbDataParameter myParameter =_dbf.GetParameter("@content", DbType.String );
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (Exception E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    Close();
                }
            
        }
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public   int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            IDbCommand cmd = _dbf.GetDBCommand(strSQL, _dbconn);
                IDbDataParameter myParameter =_dbf.GetParameter("@fs", DbType.Binary);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (Exception E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    Close();
                }
            
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public   object GetSingle(string SQLString)
        {
            using (IDbCommand cmd = _dbf.GetDBCommand(SQLString, _dbconn))
                {
                    try
                    {
                        Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (Exception e)
                    {
                        Close();
                        throw new Exception(e.Message);
                    }
                }
            
        }


        /// <summary>
        /// 执行查询语句，返回SqlDataReader(使用该方法切记要手工关闭SqlDataReader和连接)
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public   IDataReader ExecuteReader(string strSQL)
        {
            IDbCommand cmd = _dbf.GetDBCommand(strSQL, _dbconn);
            try
            {
                Open();
                IDataReader myReader =_dbf.GetDataReader( cmd);
                return myReader;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            //finally //不能在此关闭，否则，返回的对象将无法使用
            //{
            //	cmd.Dispose();
            //	Close();
            //}	


        }
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public   DataSet Query(string SQLString)
        {
            try
            {
                IDbCommand dbc = _dbf.GetDBCommand();
                if (_dbtrans != null)
                {
                    dbc.Transaction = _dbtrans;
                }
                dbc.Connection = _dbconn;
                dbc.CommandText = SQLString;
                IDbDataAdapter ida = _dbf.GetDataAdapter(dbc);
                DataSet ds = new DataSet();
                ida.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                _DBConnInfo = ex.Message;
                throw ex;
                //return null;
            }
           
        }
        /// <summary>
        /// 执行查询语句，返回DataSet,设置命令的执行等待时间
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="Times"></param>
        /// <returns></returns>
        public   DataSet Query(string SQLString, int Times)
        {
            DataSet ds = new DataSet();
                try
                {
                    Open();
		    IDbCommand dbc = _dbf.GetDBCommand();
                    if (_dbtrans != null)
                    {
                       dbc.Transaction = _dbtrans;
                    }
                    dbc.Connection = _dbconn;
                    dbc.CommandText = SQLString;
                    IDbDataAdapter command =_dbf.GetDataAdapter(dbc);
                    command.SelectCommand.CommandTimeout = Times;
                    command.Fill(ds );
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            
        }



        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public   int ExecuteSql(string SQLString, params IDbDataParameter[] cmdParms)
        {
            using (IDbCommand cmd = _dbf.GetDBCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, _dbconn, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (Exception E)
                    {
                        throw new Exception(E.Message);
                    }
                }
           
        }


        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public   void ExecuteSqlTran(Hashtable SQLStringList)
        {
            Open();
                TransBegin();
                    IDbCommand cmd = _dbf.GetDBCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            IDbDataParameter[] cmdParms = (IDbDataParameter[])myDE.Value;
                            PrepareCommand(cmd, _dbconn, _dbtrans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();

                            TransCommit();
                        }
                    }
                    catch
                    {
                        TransRollback();
                        throw;
                    }
               
            }
        


        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object  GetSingle(string SQLString, params IDbDataParameter[] cmdParms)
        {
            using (IDbCommand cmd = _dbf.GetDBCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, _dbconn, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch ( Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                }
            
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader (使用该方法切记要手工关闭SqlDataReader和连接)
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public   IDataReader ExecuteReader(string SQLString, params IDbDataParameter[] cmdParms)
        {
            
            IDbCommand cmd = _dbf.GetDBCommand();
            try
            {
                PrepareCommand(cmd, _dbconn, null, SQLString, cmdParms);
                IDataReader myReader =_dbf.GetDataReader( cmd);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            //finally //不能在此关闭，否则，返回的对象将无法使用
            //{
            //	cmd.Dispose();
            //	Close();
            //}	

        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public   DataSet Query(string SQLString, params IDbDataParameter[] cmdParms)
        {
            
                IDbCommand cmd = _dbf.GetDBCommand();
                PrepareCommand(cmd, _dbconn, null, SQLString, cmdParms);
                IDataAdapter da = _dbf.GetDataAdapter(cmd);
                
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds);
                        cmd.Parameters.Clear();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
               
             
        }


        private   void PrepareCommand(IDbCommand cmd, IDbConnection conn, IDbTransaction trans, string cmdText, 

IDbDataParameter[] cmdParms)
        {
            Open();
            cmd.Connection = _dbconn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {


                foreach (IDbDataParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == 

ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 存储过程操作

        /// <summary>
        /// 执行存储过程  (使用该方法切记要手工关闭SqlDataReader和连接)
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public   IDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            
            IDataReader returnReader;
            Open();
            IDbCommand command = BuildQueryCommand(_dbconn, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            returnReader =_dbf.GetDataReader(command );
            //Close(); 不能在此关闭，否则，返回的对象将无法使用            
            return returnReader;

        }


        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public   DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
             
                DataSet dataSet = new DataSet();
                Open();
                IDbDataAdapter sqlDA = _dbf.GetDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(_dbconn, storedProcName, parameters);
                sqlDA.Fill(dataSet );
                Close();
                return dataSet;
            
        }
        /// <summary>
        /// 获取管理任务表的主键索引
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        public  int GetManageTableIndex(string tableName)
        {
            IDbCommand command;
            IDataParameter[] arParms = new IDataParameter[3];//20101028
            arParms[0] =_dbf.GetParameter("@pTableName",DbType.String);
            arParms[0].Value = tableName;
            arParms[0].DbType = DbType.String;


            arParms[1] = _dbf.GetParameter("@pReturnValue", DbType.Int32);
            arParms[1].Direction = ParameterDirection.Output;
            arParms[1].DbType = DbType.Int32;
            arParms[2] = _dbf.GetParameter("@pKeyFieldName", DbType.String);//20101028
            arParms[2].Value = "CONTROL_APPLY_ID";//20101028
            arParms[2].DbType = DbType.String;//20101028
            try
            {
                command =BuildQueryCommand(_dbconn, "UP_GET_TABLEID", arParms);
                command.ExecuteNonQuery(); 
               
            }
            catch (Exception ex)
            {
                throw (ex);
            }

            return (int)arParms[1].Value;
        }
        public   DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
        {
           
                DataSet dataSet = new DataSet();
                Open();
                IDbDataAdapter sqlDA = _dbf.GetDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(_dbconn, storedProcName, parameters);
                sqlDA.SelectCommand.CommandTimeout = Times;
                sqlDA.Fill(dataSet);
                Close();
                return dataSet;
            
        }


        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="_dbconn">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private   IDbCommand BuildQueryCommand(IDbConnection _dbconn, string storedProcName, IDataParameter[] 

parameters)
        {
            IDbCommand command = _dbf.GetDBCommand(storedProcName, _dbconn);
            command.CommandType = CommandType.StoredProcedure;
            foreach (IDataParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == 

ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }

        ///// <summary>
        ///// 执行存储过程，返回影响的行数		
        ///// </summary>
        ///// <param name="storedProcName">存储过程名</param>
        ///// <param name="parameters">存储过程参数</param>
        ///// <param name="rowsAffected">影响的行数</param>
        ///// <returns></returns>
        //public   int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        //{
             
        //        int result;
        //        Open();
        //        IDbCommand command = BuildIntCommand(_dbconn, storedProcName, parameters);
        //        rowsAffected = command.ExecuteNonQuery();
        //        result = (int)command.Parameters["ReturnValue"].Value;
        //        //Close();
        //        return result;
             
        //}

        ///// <summary>
        ///// 创建 SqlCommand 对象实例(用来返回一个整数值)	
        ///// </summary>
        ///// <param name="storedProcName">存储过程名</param>
        ///// <param name="parameters">存储过程参数</param>
        ///// <returns>SqlCommand 对象实例</returns>
        //private   IDbCommand BuildIntCommand(IDbConnection _dbconn, string storedProcName, IDataParameter[] parameters)
        //{
        //    IDbCommand command = BuildQueryCommand(_dbconn, storedProcName, parameters);
        //    command.Parameters.Add(_dbf.GetParameter("ReturnValue",
        //        SqlDbType.Int, 4, ParameterDirection.ReturnValue,
        //        false, 0, 0, string.Empty, DataRowVersion.Default, null));
        //    return command;
        //}
        #endregion

        
        #endregion

    }
}
