using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;


namespace KstCmsBase.DAL
{
    public class Access
    {
        string Mdb_connstr = string.Empty;
       // string Sql_commstr = string.Empty;
        public System.Data.OleDb.OleDbConnection dbconn = null;
        public Access()
        {
            string dbpath = WebConfigurationManager.AppSettings["DBPath"];
            Mdb_connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath(dbpath);
            dbconn = new System.Data.OleDb.OleDbConnection(Mdb_connstr);
            if (dbconn.State == System.Data.ConnectionState.Closed)
                dbconn.Open();

        }




        public System.Data.DataSet ExecuteDataSet(string sqlstr)
        {
            if (dbconn.State == System.Data.ConnectionState.Closed)
                dbconn.Open();
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sqlstr, dbconn);

            System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter(cmd);
            System.Data.DataSet ds = new System.Data.DataSet();
            Da.Fill(ds);
            return ds;

        }

        public System.Data.OleDb.OleDbDataReader ExecuteDataReader(string sqlstr)
        {
            if (dbconn.State == System.Data.ConnectionState.Closed)
                dbconn.Open();
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sqlstr, dbconn);
            System.Data.OleDb.OleDbDataReader rs = null;
            rs = cmd.ExecuteReader();
            return rs;
        }

        public System.Data.OleDb.OleDbDataAdapter ExecuteDataAdapter(string sqlstr, out int rowCount)
        {
            if (dbconn.State == System.Data.ConnectionState.Closed)
                dbconn.Open();

            System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter(sqlstr, dbconn);
            DataSet ds = new DataSet();
            Da.Fill(ds);
            rowCount = ds.Tables[0].Rows.Count;
            ds.Dispose();
            return Da;
        }

        public string getFieldValue(string sql)
        {
            string Result = null;
            System.Data.OleDb.OleDbDataReader dr = ExecuteDataReader(sql);
            if (dr.Read())
            {
                Result = dr[0].ToString();
            }
            dr.Close();
            dr.Dispose();
            return Result;
        }

        public string Get_DbSQL(string FromAndWhere, params string[] Fields)
        {
            StringBuilder SelectFields = new StringBuilder();
            if (Fields.Length > 0)
            {
                foreach (string str in Fields)
                {
                    SelectFields.Append(str + ",");  
                }
                SelectFields.Remove(SelectFields.Length - 1, 1);
            }
            else
            {
                SelectFields.Append("*");
            }
            SelectFields.Insert(0, "select ");
            SelectFields.Append(" " + FromAndWhere);
            return SelectFields.ToString();
        }

        public string Get_DbSQL(string FromAndWhere,int TopNum, params string[] Fields)
        {
            StringBuilder SelectFields = new StringBuilder();
            if (Fields.Length > 0)
            {
                foreach (string str in Fields)
                {
                    SelectFields.Append(str + ",");
                }
                SelectFields.Remove(SelectFields.Length - 1, 1);
            }
            else
            {
                SelectFields.Append("*");
            }
            SelectFields.Insert(0, "select top " + TopNum.ToString() + " ");
            SelectFields.Append(" " + FromAndWhere);
            return SelectFields.ToString();
        }

        private System.Data.OleDb.OleDbType Get_dbType(string TableName, string Field, ref int myTableFieldSize,ref object FieldValue)
        {
            string sql = string.Format("select top 1 {0} from {1}", Field, TableName);
            System.Data.OleDb.OleDbDataReader dr = ExecuteDataReader(sql);
            string myTableFieldType=dr.GetDataTypeName(0);
            
            System.Data.OleDb.OleDbType tmpType = System.Data.OleDb.OleDbType.VarChar;
            switch (myTableFieldType)
            {
                case "System.String":
                    {
                        tmpType = System.Data.OleDb.OleDbType.VarChar;
                        myTableFieldSize = FieldValue.ToString().Length;
                        FieldValue = FieldValue.ToString();
                        break;
                    }
                case "System.Decimal":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Decimal;
                        myTableFieldSize = 10;
                        FieldValue = Convert.ToDecimal(FieldValue.ToString());
                        break;
                    }
                case "System.DateTime":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Date;
                        myTableFieldSize = 12;
                        FieldValue = Convert.ToDateTime(FieldValue.ToString());
                        break;
                    }
                case "System.Double":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Double;
                        myTableFieldSize = 8;
                        FieldValue = Convert.ToDouble(FieldValue.ToString());
                        break;
                    }
                case "System.Int32":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Integer;
                        myTableFieldSize = 4;
                        FieldValue = Convert.ToInt32(FieldValue.ToString());
                        break;
                    }
                case "System.Boolean":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Boolean;
                        myTableFieldSize = 1;
                        FieldValue = Convert.ToBoolean(FieldValue);
                        break;
                    }
            }
            return tmpType;

        }

        public int DataInsert(string[] FieldValues,object TableName,params string[] Fields)
        {

            int ActRow = 0;
            StringBuilder SelectFields = new StringBuilder();
            StringBuilder ValueFields = new StringBuilder();
            if (Fields.Length > 0)
            {
                foreach (string str in Fields)
                {
                    SelectFields.Append(str + ",");
                    ValueFields.Append("@" + str + ",");
                    
                }
                SelectFields.Remove(SelectFields.Length - 1, 1);
                ValueFields.Remove(ValueFields.Length - 1, 1);
            }
            else
            {
                throw new Exception("Fields Error!"); 
            }
            string sql = string.Format("insert into {0}({1}) values({2})", TableName.ToString(), SelectFields.ToString(), ValueFields.ToString());
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbconn);
            for(int i=0;i<Fields.Length;i++)
            {

                int FieldSize=0;
                object FieldValue=FieldValues[i];
                System.Data.OleDb.OleDbType DbType = Get_dbType(TableName.ToString(),Fields[i],ref FieldSize,ref FieldValue);
                cmd.Parameters.Add("@" + Fields[i], DbType, FieldSize).Value = FieldValue;
            }
            try
            {
                ActRow = cmd.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                cmd.Dispose();
                Dispose();
                throw new Exception(err.Message);
            }
            finally
            {
                cmd.Dispose();
                Dispose();
            }
            return ActRow;


        }

        /// <summary>
        /// 更新数据表
        /// </summary>
        /// <param name="FieldValues">要更新的数据值</param>
        /// <param name="TableName">要更新的数据表</param>
        /// <param name="IDField">索引字段名</param>
        /// <param name="IDFieldValue">索引字段值where 索引字段名=IDFieldValue</param>
        /// <param name="Fields">要更新的字段名</param>
        /// <returns></returns>
        
        public int DataUpdate(string TableName, string IndexField, int IndexFieldValue, string[] UpdateFieldValue, params string[] Fields)
        {

            int ActRow = 0;
            StringBuilder SelectFields = new StringBuilder();
            if (Fields.Length > 0)
            {
                foreach (string str in Fields)
                {
                    SelectFields.Append(str + "=@" + str + ",");
                   

                }
                SelectFields.Remove(SelectFields.Length - 1, 1);
            }
            else
            {
                throw new Exception("Fields Error!");
            }
            string sql = string.Format("update {0} set {1} where {2}={3}", TableName.ToString(), SelectFields.ToString(), IndexField, IndexFieldValue);
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbconn);
            for (int i = 0; i < Fields.Length; i++)
            {

                int FieldSize = 0;
                object FieldValue = UpdateFieldValue[i];
                System.Data.OleDb.OleDbType DbType = Get_dbType(TableName.ToString(), Fields[i], ref FieldSize, ref FieldValue);
                cmd.Parameters.Add("@" + Fields[i], DbType, FieldSize).Value = FieldValue;
            }
            try
            {
                ActRow = cmd.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                throw new Exception("更新错误:请与管理员联系！\n\n" + err.Message);
            }
            finally
            {
                cmd.Dispose();
                Dispose();
            }
            return ActRow;


        }

        /// <summary>
        /// 更新数据表
        /// </summary>
        /// <param name="TableName">要更新的数据表</param>
        /// <param name="IDField">索引字段名</param>
        /// <param name="IDFieldValue">索引字段值</param>
        /// <param name="FieldValues">将要更新的字段值</param>
        /// <param name="Fields">将要更新的字段名</param>
        /// <returns></returns>
        public int DataUpdate(string TableName, string IndexField, string IndexFieldValue, string[] UpdateFieldValue, params string[] Fields)
        {

            int ActRow = 0;
            StringBuilder SelectFields = new StringBuilder();
            if (Fields.Length > 0)
            {
                foreach (string str in Fields)
                {
                    SelectFields.Append(str + "=@" + str + ",");


                }
                SelectFields.Remove(SelectFields.Length - 1, 1);
            }
            else
            {
                throw new Exception("Fields Error!");
            }
            string sql = string.Format("update {0} set {1} where {2}='{3}'", TableName.ToString(), SelectFields.ToString(), IndexField, IndexFieldValue);
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbconn);
            for (int i = 0; i < Fields.Length; i++)
            {

                int FieldSize = 0;
                object FieldValue = UpdateFieldValue[i];
                System.Data.OleDb.OleDbType DbType = Get_dbType(TableName.ToString(), Fields[i], ref FieldSize, ref FieldValue);
                cmd.Parameters.Add("@" + Fields[i], DbType, FieldSize).Value = FieldValue;
            }
            try
            {
                ActRow = cmd.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                throw new Exception("更新错误:请与管理员联系！\n\n" + err.Message);
            }
            finally
            {
                cmd.Dispose();
                Dispose();
            }
            return ActRow;


        }

        public int DataDelete(string TableName, string IDField, string IDFieldValue)
        {
            int ActRow = 0;
            string sql = string.Format("delete from {0} where {1}='{2}'", TableName, IDField, IDFieldValue);
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbconn);
            try
            {
                ActRow = cmd.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);

            }
            finally
            {
                cmd.Dispose();
                Dispose();
            }
            return ActRow;
        }

        public int DataDelete(string TableName, string IDField, int IDFieldValue)
        {
            if (dbconn.State == System.Data.ConnectionState.Closed)
                dbconn.Open();
            int ActRow = 0;
            string sql = string.Format("delete from {0} where {1}={2}", TableName, IDField, IDFieldValue.ToString());
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbconn);
            try
            {
                ActRow = cmd.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);

            }
            finally
            {
                cmd.Dispose();
                Dispose();
            }
            return ActRow;
        }

        public void GetField(DataRow Row, string FieldName,ref DataTable Dt)
        {
            string  FieldValue=Row[FieldName].ToString();
            DataColumn dtCol = new DataColumn();
            dtCol.ColumnName = FieldName;
            dtCol.DataType = Row[FieldName].GetType();
            Dt.Columns.Add(dtCol);
            Dt.Rows[0][FieldName] = FieldValue;    
        }

        public int ExecuteSql(string sql)
        {
            int ActRow = 0;
            if (dbconn.State == System.Data.ConnectionState.Closed)
                dbconn.Open();
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbconn);
            try
            {
                ActRow = cmd.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                throw new Exception("执行ExecuteSQL时错误:请与管理员联系！\n\n" + err.Message);
            }
            finally
            {
                cmd.Dispose();
                Dispose();
            }
            return ActRow;
        }


        public void Dispose()
        {
            if (dbconn.State == System.Data.ConnectionState.Open)
                dbconn.Close();
        }


    }


}
