using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web;


/// <summary>
/// Copyright (C) Maticsoft
/// 数据访问基础类(基于OleDb)
/// 可以用户可以修改满足自己项目的需要。
/// </summary>
public abstract class DbHelperOleDb
{
    //数据库连接字符串(web.config来配置)，可以动态更改connectionString支持多数据库.		
    public static string connectionString
    {
        get
        {
            return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AccessPath"]) + ";Persist Security Info=False;";
        }
    }

    public DbHelperOleDb()
    {
    }


    #region 获取最大IDGetMaxID
    /// <summary>
    /// 获取最大IDGetMaxID
    /// </summary>
    /// <param name="FieldName"></param>
    /// <param name="TableName"></param>
    /// <returns></returns>
    public static int GetMaxID(string FieldName, string TableName)
    {
        string strsql = "select max(" + FieldName + ")+1 from " + TableName;
        object obj = DbHelperOleDb.ExecuteScalar(CommandType.Text, strsql, null);
        if (obj == null)
        {
            return 1;
        }
        else
        {
            return int.Parse(obj.ToString());
        }
    }
    #endregion

    #region 是否存在Exists
    /// <summary>
    /// 是否存在Exists
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public static bool Exists(string strSql)
    {
        object obj = DbHelperOleDb.ExecuteScalar(CommandType.Text, strSql, null);
        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="SQLStringList">多条SQL语句</param>		
    public static void ExecuteSqlTran(string[] SQLStringList)
    {
        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            conn.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;
            OleDbTransaction tx = conn.BeginTransaction();
            cmd.Transaction = tx;
            try
            {
                for (int n = 0; n < SQLStringList.Length; n++)
                {
                    string strsql = SQLStringList[n].ToString();
                    if (strsql.Trim().Length > 1)
                    {
                        cmd.CommandText = strsql;
                        cmd.ExecuteNonQuery();
                    }
                }
                tx.Commit();
            }
            catch (System.Data.OleDb.OleDbException E)
            {
                tx.Rollback();
                throw new Exception(E.Message);
            }
        }
    }
    #endregion

    #region 执行ExecuteNonQuery
    /// <summary>
    /// 用于执行一段SQL语句。
    /// To excute a SQL statement, which reuturns a integer stand for effect line number.
    /// </summary>
    /// <param name="connString">连接字符串 (Connection String)</param>
    /// <param name="cmdType">command的字符串 (SQL Statement)</param>
    /// <param name="cmdText">command的类型，具体见：CommandType (Command type)</param>
    /// <param name="cmdParms">参数列表 (Paramters)</param>
    /// <returns>返回影响行数 (effect line number)</returns>
    public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params OleDbParameter[] cmdParms)
    {

        OleDbCommand cmd = new OleDbCommand();

        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }
    }

    #endregion

    #region 执行ExecuteReader

    /// <summary>
    /// 用于执行一个Select语句返回一个datareader
    /// To excute a SQL statement, and reuturns a dataReader.
    /// </summary>
    /// <param name="connString">连接字符串 (Connection String)</param>
    /// <param name="cmdType">command的字符串 (SQL Statement)</param>
    /// <param name="cmdText">command的类型，具体见：CommandType (Command type)</param>
    /// <param name="cmdParms">参数列表 (Paramters)</param>
    /// <returns>dataReader</returns>
    public static OleDbDataReader ExecuteDataReader(CommandType cmdType, string cmdText, params OleDbParameter[] cmdParms)
    {

        OleDbCommand cmd = new OleDbCommand();

        OleDbConnection conn = new OleDbConnection(connectionString);

        // we use a try/catch here because if the method throws an exception we want to 
        // close the connection throw code, because no datareader will exist, hence the 
        // commandBehaviour.CloseConnection will not work
        try
        {
            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            OleDbDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            //				cmd.Parameters.Clear();
            return rdr;
        }
        catch
        {
            conn.Close();
            throw;
        }
    }

    #endregion

    #region 执行ExecuteScalar
    /// <summary>
    /// 用于读取一个值，查询所返回的是结果集中第一行的第一列
    /// To excute a SQL statement, and returns the first column of the first line
    /// </summary>
    /// <param name="connString">连接字符串 (Connection String)</param>
    /// <param name="cmdType">command的字符串 (SQL Statement)</param>
    /// <param name="cmdText">command的类型，具体见：CommandType (Command type)</param>
    /// <param name="cmdParms">参数列表 (Paramters)</param>
    /// <returns>the first column of the first line</returns>
    public static object ExecuteScalar(CommandType cmdType, string cmdText, params OleDbParameter[] cmdParms)
    {
        OleDbCommand cmd = new OleDbCommand();

        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }
    }
    #endregion

    #region 执行ExecuteDataSet
    public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
    {
        OleDbConnection conn = new OleDbConnection(connectionString);
        OleDbCommand cmd = new OleDbCommand();
        try
        {
            //操作SqlCommand
            PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
            //执行
            OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds);

            //关闭数据库
            conn.Close();
            //清理参数
            cmd.Parameters.Clear();
            return ds;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

    #region ExecuteDataAdapter 适配器OleDbDataAdapter
    /// <summary>
    /// 返回OleDbDataAdapter
    /// </summary>
    /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
    /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
    /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
    /// <returns>返回OleDbDataAdapter；失败返回null</returns>
    public static OleDbDataAdapter ExecuteDataAdapter(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
    {
        OleDbCommand cmd = new OleDbCommand();
        OleDbConnection conn = new OleDbConnection(connectionString);
        try
        {
            //操作SqlCommand
            PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
            //执行
            OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
            //关闭数据库
            conn.Close();
            return sda;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion


    #region 执行PrepareCommand

    /// <summary>
    /// 在执行SQL语句之前的准备工作
    /// </summary>
    /// <param name="cmd">command</param>
    /// <param name="conn">connection</param>
    /// <param name="trans">trasaction</param>
    /// <param name="cmdType">command类型</param>
    /// <param name="cmdText">command字符串</param>
    /// <param name="cmdParms">参数列表</param>
    private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, CommandType cmdType, string cmdText, OleDbParameter[] 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 (OleDbParameter parm in cmdParms)
                cmd.Parameters.Add(parm);
        }
    }

    #endregion



}

