C# 数据库类 值得一看

 
//===============================================================================
// This file is based on the Microsoft Data Access Application Block for .NET
// For more information please go to 
// http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
//===============================================================================

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;

namespace PetShop.DBUtility {

    /** <summary>
    /// The SqlHelper class is intended to encapsulate high performance, 
    /// scalable best practices for common uses of SqlClient.
    /// </summary>
    public abstract class SqlHelper {

        //Database connection strings
        public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["SQLConnString1"].ConnectionString;
        public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString2"].ConnectionString;
        public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString3"].ConnectionString;
        public static readonly string ConnectionStringProfile = ConfigurationManager.ConnectionStrings["SQLProfileConnString"].ConnectionString;        
        
        // Hashtable to store cached parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /** <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

            SqlCommand cmd = new SqlCommand();

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

        /** <summary>
        /// Execute a SqlCommand (that returns no resultset) against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /** <summary>
        /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">an existing sql transaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /** <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(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, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch {
                conn.Close();
                throw;
            }
        }

        /** <summary>
        /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString)) {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /** <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            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 SqlParameter[] commandParameters) {
            parmCache[cacheKey] = commandParameters;
        }

        /** <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey) {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /** <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] 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 (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
    }
}

oracle helper
using System;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using System.Collections;

namespace PetShop.DBUtility {

    /** <summary>
    /// A helper class used to execute queries against an Oracle database
    /// </summary>
    public abstract class OracleHelper {

        // Read the connection strings from the configuration file
        public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["OraConnString1"].ConnectionString;
        public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.ConnectionStrings["OraConnString2"].ConnectionString;
        public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["OraConnString3"].ConnectionString;
        public static readonly string ConnectionStringProfile = ConfigurationManager.ConnectionStrings["OraProfileConnString"].ConnectionString;
        public static readonly string ConnectionStringMembership = ConfigurationManager.ConnectionStrings["OraMembershipConnString"].ConnectionString;

        //Create a hashtable for the parameter cached
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /** <summary>
        /// Execute a database query which does not include a select
        /// </summary>
        /// <param name="connString">Connection string to database</param>
        /// <param name="cmdType">Command type either stored procedure or SQL</param>
        /// <param name="cmdText">Acutall SQL Command</param>
        /// <param name="commandParameters">Parameters to bind to the command</param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) {
            // Create a new Oracle command
            OracleCommand cmd = new OracleCommand();

            //Create a connection
            using (OracleConnection connection = new OracleConnection(connectionString)) {

                //Prepare the command
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);

                //Execute the command
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /** <summary>
        /// Execute an OracleCommand (that returns no resultset) against an existing database transaction 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24));
        /// </remarks>
        /// <param name="trans">an existing database transaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or PL/SQL command</param>
        /// <param name="commandParameters">an array of OracleParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(OracleTransaction trans, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) {
            OracleCommand cmd = new OracleCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /** <summary>
        /// Execute an OracleCommand (that returns no resultset) against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or PL/SQL command</param>
        /// <param name="commandParameters">an array of OracleParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(OracleConnection connection, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) {

            OracleCommand cmd = new OracleCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /** <summary>
        /// Execute a select query that will return a result set
        /// </summary>
        /// <param name="connString">Connection string</param>
         <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or PL/SQL command</param>
        /// <param name="commandParameters">an array of OracleParamters used to execute the command</param>
        /// <returns></returns>
        public static OracleDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) {

            //Create the command and connection
            OracleCommand cmd = new OracleCommand();
            OracleConnection conn = new OracleConnection(connectionString);

            try {
                //Prepare the command to execute
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);

                //Execute the query, stating that the connection should close when the resulting datareader has been read
                OracleDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;

            }
            catch {

                //If an error occurs close the connection as the reader will not be used and we expect it to close the connection
                conn.Close();
                throw;
            }
        }

        /** <summary>
        /// Execute an OracleCommand that returns the first column of the first record against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or PL/SQL command</param>
        /// <param name="commandParameters">an array of OracleParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) {
            OracleCommand cmd = new OracleCommand();

            using (OracleConnection conn = new OracleConnection(connectionString)) {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /**    <summary>
        ///    Execute    a OracleCommand (that returns a 1x1 resultset)    against    the    specified SqlTransaction
        ///    using the provided parameters.
        ///    </summary>
        ///    <param name="transaction">A    valid SqlTransaction</param>
        ///    <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
        ///    <param name="commandText">The stored procedure name    or PL/SQL command</param>
        ///    <param name="commandParameters">An array of    OracleParamters used to execute the command</param>
        ///    <returns>An    object containing the value    in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(OracleTransaction transaction, CommandType commandType, string commandText, params OracleParameter[] commandParameters) {
            if(transaction == null)
                throw new ArgumentNullException("transaction");
            if(transaction != null && transaction.Connection == null)
                throw new ArgumentException("The transaction was rollbacked    or commited, please    provide    an open    transaction.", "transaction");

            // Create a    command    and    prepare    it for execution
            OracleCommand cmd = new OracleCommand();

            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

            // Execute the command & return    the    results
            object retval = cmd.ExecuteScalar();

            // Detach the SqlParameters    from the command object, so    they can be    used again
            cmd.Parameters.Clear();
            return retval;
        }

        /** <summary>
        /// Execute an OracleCommand that returns the first column of the first record against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(conn, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or PL/SQL command</param>
        /// <param name="commandParameters">an array of OracleParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(OracleConnection connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) {
            OracleCommand cmd = new OracleCommand();

            PrepareCommand(cmd, connectionString, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        /** <summary>
        /// Add a set of parameters to the cached
        /// </summary>
        /// <param name="cacheKey">Key value to look up the parameters</param>
        /// <param name="commandParameters">Actual parameters to cached</param>
        public static void CacheParameters(string cacheKey, params OracleParameter[] commandParameters) {
            parmCache[cacheKey] = commandParameters;
        }

        /** <summary>
        /// Fetch parameters from the cache
        /// </summary>
        /// <param name="cacheKey">Key to look up the parameters</param>
        /// <returns></returns>
        public static OracleParameter[] GetCachedParameters(string cacheKey) {
            OracleParameter[] cachedParms = (OracleParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            // If the parameters are in the cache
            OracleParameter[] clonedParms = new OracleParameter[cachedParms.Length];

            // return a copy of the parameters
            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (OracleParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /** <summary>
        /// Internal function to prepare a command for execution by the database
        /// </summary>
        /// <param name="cmd">Existing command object</param>
        /// <param name="conn">Database connection object</param>
        /// <param name="trans">Optional transaction object</param>
        /// <param name="cmdType">Command type, e.g. stored procedure</param>
        /// <param name="cmdText">Command test</param>
        /// <param name="commandParameters">Parameters for the command</param>
        private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, CommandType cmdType, string cmdText, OracleParameter[] commandParameters) {

            //Open the connection if required
            if (conn.State != ConnectionState.Open)
                conn.Open();

            //Set up the command
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandType = cmdType;

            //Bind it to the transaction if it exists
            if (trans != null)
                cmd.Transaction = trans;

            // Bind the parameters passed in
            if (commandParameters != null) {
                foreach (OracleParameter parm in commandParameters)
                    cmd.Parameters.Add(parm);
            }
        }

        /** <summary>
        /// Converter to use boolean data type with Oracle
        /// </summary>
        /// <param name="value">Value to convert</param>
        /// <returns></returns>
        public static string OraBit(bool value) {
            if(value)
                return "Y";
            else
                return "N";
        }

        /** <summary>
        /// Converter to use boolean data type with Oracle
        /// </summary>
        /// <param name="value">Value to convert</param>
        /// <returns></returns>
        public static bool OraBool(string value) {
            if(value.Equals("Y"))
                return true;
            else
                return false;
        } 
    }
}


using System;
using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace Util
{
 /** <summary>
 /// Util
 /// 连接数据库层
 /// </summary>
 public class ConDB
 {
  变量#region 变量
  private SqlConnection con;
  string strCon="server=.;database=blog;uid=sa;pwd=";
  string ErrLogPath="错误存放的路径";
  #endregion
  public ConDB()
  {
  }

  连接数据库#region 连接数据库
  /** <summary>
  /// 连接数据库
  /// </summary>
  /// <param name="strCon">连接数据库的字符串</param>
  /// <returns></returns>
  public SqlConnection getConnection(string strCon)
  {
   try
   {
    SqlConnection con=new SqlConnection(strCon);
    con.Open();
    return con;
   }
   catch(Exception ee)
   {
    FileStream fs=new FileStream(this.ErrLogPath,System.IO.FileMode.Append );
    StreamWriter sw=new StreamWriter(fs);
    sw.WriteLine("**************************************************");
    sw.WriteLine("错误日期:"+System.DateTime.Now);
    sw.WriteLine("错误描述:"+ee.Message);
    sw.WriteLine("错误名称:"+ee.Source);
    sw.WriteLine("详细:"+ee.ToString());
    sw.WriteLine("*************************************************");
    sw.Close(); 
    return null;
   }
  }
  #endregion
  执行SQL语句,添加,删除,修改都可以#region 执行SQL语句,添加,删除,修改都可以
  /** <summary>
  /// 执行SQL语句,添加,删除,修改都可以
  /// </summary>
  /// <param name="sql">sql语句</param>
  /// <returns>1表示成功,0表示失败</returns>
  public int ExecSql(string sql)
  {
   try
   {
    con=this.getConnection(this.strCon);
    SqlCommand cmd=con.CreateCommand();
    cmd.CommandText =sql;
    int i=cmd.ExecuteNonQuery();
    con.Close();
    return i;
   }
   catch(Exception ee)
   {
    this.WriteErrFile(ee);
    return 0;
   }
   finally
   {
   }
  }
  #endregion
  用来查询的,可以用来判断用户是否在数据库中存在#region 用来查询的,可以用来判断用户是否在数据库中存在
  /** <summary>
  /// 用来查询的,可以用来判断用户是否在数据库中存在
  /// 
  /// </summary>
  /// <param name="sql"></param>
  /// <returns></returns>
  public SqlDataReader SelectSql(string sql)
  {
   try
   {
    con=this.getConnection(this.strCon);
    SqlCommand cmd=con.CreateCommand();
    cmd.CommandText=sql;
    SqlDataReader sr=cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection );
    return sr;
   }
   catch(Exception ee)
   {
  this.WriteErrFile(ee);
    return null;
   }
   
  }
  #endregion
  执行存储过程返回影响的行数#region 执行存储过程返回影响的行数
  /** <summary>
  /// 执行存储过程
  /// </summary>
  /// <param name="procName">存储过程名</param>
  /// <param name="sp">存储过程参数</param>
  /// <returns>1成功,0,失败</returns>
  public int ExecuteProc(string procName,SqlParameter []sp)
  {
   con = this.getConnection(this.strCon);
   //con.Open();
   SqlCommand sqlCmd = con.CreateCommand();
   sqlCmd.CommandText = procName;
   sqlCmd.CommandType = CommandType.StoredProcedure;
   foreach(SqlParameter s in sp)
   {
    sqlCmd.Parameters.Add(s);
   }
   try
   {
    int i=sqlCmd.ExecuteNonQuery();
    con.Close();
    return i;
   }
   catch(System.Exception ee)
   {
   this.WriteErrFile(ee);
    return 0;
   }
  }

  #endregion
  

  执行语句#region 执行语句
  public int ExecteSql(string sql,SqlParameter[] sp)
  {
   con = this.getConnection(this.strCon);
   //con.Open();
   SqlCommand sqlCmd = con.CreateCommand();
   sqlCmd.CommandText = sql;
   //sqlCmd.CommandType = CommandType.StoredProcedure;
   foreach(SqlParameter s in sp)
   {
    sqlCmd.Parameters.Add(s);
   }
   try
   {
    int i=sqlCmd.ExecuteNonQuery();
    con.Close();
    return i;
   }
   catch(System.Exception ee)
   {
   this.WriteErrFile(ee);
    return 0;
   }
  }
  #endregion
  执行存储过程,返回DataSet#region 执行存储过程,返回DataSet
  /** <summary>
  /// 执行存储过程,返回DataSet
  /// </summary>
  /// <param name="procname">执行存储过程名</param>
  /// <param name="sp">执行存储过程参数</param>
  /// <param name="tablename">表名</param>
  /// <returns>DataSet</returns>
  public DataSet GetDataSet(string procname,SqlParameter[] sp)
  {
   con =this.getConnection(this.strCon );   
   SqlCommand cmd =new SqlCommand();
   SqlDataAdapter da=new SqlDataAdapter();
   DataSet ds=new DataSet();
   cmd.CommandText=procname;
   cmd.CommandType=CommandType.StoredProcedure;      
   try
   {
    //con.Open();
    cmd.Connection=con;   
    foreach (SqlParameter p in sp)
    {
     if(p==null)
      break;
     cmd.Parameters.Add(p);
    }
    cmd.ExecuteNonQuery();
    da.SelectCommand=cmd;
    da.Fill(ds);
    con.Close();
    return ds;
   }
   catch(System.Data.SqlClient.SqlException ee)
   {
    this.WriteErrFile(ee);
    return null;
   }
  }

  #endregion
  分页用的DataSet#region 分页用的DataSet
  public DataSet getPageDataSet(string sql,int begin,int maxR,string tablename)
  {
   try
   {
    DataSet ds=new DataSet();
    SqlDataAdapter sa=new SqlDataAdapter(sql,this.strCon);
    sa.Fill(ds, begin, maxR,tablename);
    return ds;
   }
   catch(System.Exception ee)
   {
    this.WriteErrFile(ee);
    return null;
   }
  }

  #endregion
  执行一个参数的存储过程#region 执行一个参数的存储过程
  public DataSet getDataSet(SqlParameter p,string procName)
  {
   try
   {
    con=this.getConnection(this.strCon);
    SqlCommand cmd=con.CreateCommand();
    cmd.CommandText =procName;
    //cmd.Parameters.Add("@wj",SqlDbType.Int).value="/i;
    cmd.CommandType=CommandType.StoredProcedure;
    cmd.Parameters.Add(p);
    //cmd.ExecuteReader();
    System.Data.SqlClient.SqlDataAdapter" sa=new SqlDataAdapter();
    sa.SelectCommand=cmd;
    DataSet ds=new DataSet();
    sa.Fill(ds);
    return ds;
    //ds=dss;


   }
   catch(System.Data.SqlClient.SqlException ee)
   {
    this.WriteErrFile(ee);
    return null;
   }
  }
  #endregion
  把错误写入文件方法#region 把错误写入文件方法
  public void WriteErrFile(Exception ee)
  {
   FileStream fs=new FileStream(this.ErrLogPath,System.IO.FileMode.Append );
   StreamWriter sw=new StreamWriter(fs);
   sw.WriteLine("**************************************************");
   sw.WriteLine("错误日期:"+System.DateTime.Now);
   sw.WriteLine("错误描述:"+ee.Message);
   sw.WriteLine("错误名称:"+ee.Source);
   sw.WriteLine("详细:"+ee.ToString());
   sw.WriteLine("*************************************************");
   sw.Close(); 
  
  }
  #endregion
  用sql语句返回DataSet#region 用sql语句返回DataSet
  /** <summary>
  /// 用sql语句返回DataSet
  /// </summary>
  /// <param name="sql">连接字符串</param>
  /// <returns>DataSet</returns>
  public DataSet GetDataSet(string sql)
  {
   try
   {
    SqlDataAdapter sda = new SqlDataAdapter(sql,this.strCon);
    DataSet ds = new DataSet();
    sda.Fill(ds);
    return ds;
   }
   catch(System.Data.SqlClient.SqlException ee)
   {
    this.WriteErrFile(ee);
    return null;
   }
  }
 }
 #endregion
 

}





namespace Common
{
    /** <summary>
    /// 自定义的类库
    /// </summary>
    public class MyClass
    {
        public static string    CONN_STR;                //自动生成的连接字符串

        const  string MYKEY        = "test";                    //用于加密解密的密钥
        const  string UID        = "sa";                        //用于联接数据库的用户名
        const  string PWD        = "";                        //用于联接数据库的密码
        const  string DATABASE  = "NorthWind";                //登录服务器的数据库名

        
        //通过DLL调用进行读写INI文件的API        
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);
        [DllImport("kernel32")]
        private static extern int  GetPrivateProfileString(string section,string key,string def, StringBuilder retVal,int size,string filePath);


        public MyClass()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }


        OpenProc ExecProc 自定义的执行指定存储过程的过程#region OpenProc ExecProc 自定义的执行指定存储过程的过程
        public static DataSet OpenProc(SqlCommand MySqlCommand, DataGrid MyDataGrid,string MyTableName)
        {    //string[,] myArray = new string[4,2];
            //启用异常处理
            try 
            {
                //先建立一个数据库联接
                SqlConnection mySqlConnection = new SqlConnection (CONN_STR);
            
                //再指定SqlCommand对象的Connection属性
                MySqlCommand.Connection = mySqlConnection;

                //再建立一个SqlDataAdapter对象,并把它指向MySqlCommand
                SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
                mySqlDataAdapter.SelectCommand  = MySqlCommand;

                //最后再建立一个DataSet对象
                DataSet myDataSet = new DataSet();
            
                //打开数据库联接
                mySqlConnection.Open();

                //执行填充操作
                mySqlDataAdapter.Fill(myDataSet,"Test"); 

                //关闭数据库联接
                mySqlConnection.Close();

                //把dataGrid与DataSet联接起来,注意这里的写法,[]中的内容非常重要
                if (MyDataGrid != null)
                {
                    //以数据绑定的方式设置数据源
                    //MyDataGrid.SetDataBinding(myDataSet, "Test");

                    //直接设置表格的数据源
                    int iTableCount = myDataSet.Tables.Count;
                    if (iTableCount > 0)
                    {
                        MyDataGrid.DataSource = myDataSet.Tables[0];
                        if ((MyTableName != null) && (MyTableName != ""))
                        {
                            //自动转换表格的标题
                            string [,] ht = GetColText(MyTableName);
                            if (ht!=null)
                            {
                                SetColText(myDataSet.Tables[0],MyDataGrid,ht);        
                            }
                        }
                    }
                }

                //返回DataSet
                return myDataSet;
            }

            catch (Exception e)
            {
                
                string ErrMsg = "       操作发生异常错误,错误内容如下"        + (char)13 + 
                    "--------------------------------------------" + (char)13 +
                    "错误原因:"  +    e.Message + (char)13 +
                    "错 误 源:"  + e.Source  + (char)13 +
                    "帮助信息:"  + e.HelpLink;
                MessageBox.Show(ErrMsg,"错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return null;
            }
        }
        
        
        public static int ExecProc(SqlCommand MySqlCommand, DataGrid MyDataGrid,string MyTableName)
        {    //先定义一个DataSet变量
            DataSet myDataSet = new DataSet();  
            //执行存储过程
            myDataSet     = OpenProc(MySqlCommand,MyDataGrid,MyTableName);
            //如果执行成功,有结果返回,则返回该结果的记录行数
            if (myDataSet != null)
            {
                if ( myDataSet.Tables.Count > 0)
                    return myDataSet.Tables[0].Rows.Count;
                else if (MyDataGrid != null)
                    return -1;
                else return 0;
            }
            else
                return -1;
        }


        #endregion


        自定义的取得某表的所有列的中文名的过程#region 自定义的取得某表的所有列的中文名的过程
        public static string[,] GetColText(string strTableName)
        {
            //先建立一个SqlCommand对象和DataSetd对象
            SqlCommand mySqlCommand  = new SqlCommand();
            DataSet    myDataSet     = new DataSet();  
            
            //设置好要调用的存储过程及参数,注意这里的写法
            mySqlCommand.CommandText =" exec xp_GetColumnText @p_TableName,@p_RowCount output";
            mySqlCommand.Parameters.Add("@p_TableName" , SqlDbType.VarChar).Value = strTableName;
            mySqlCommand.Parameters.Add("@p_RowCount" ,  SqlDbType.Int);
            mySqlCommand.Parameters["@p_RowCount"].Direction=System.Data.ParameterDirection.Output;

            //执行存储过程,并返回结果集
            myDataSet     = OpenProc(mySqlCommand,null,strTableName);
            int iRowCount = myDataSet.Tables[0].Rows.Count;

            //把Grid中的数据取出并返回
            if (iRowCount > 0)
            {
                string [,] strResult = new string[iRowCount,2];

                for(int i=0; i<iRowCount; i++)
                {
                    strResult[i,0]=(string)myDataSet.Tables[0].Rows[i].ItemArray[0];
                    strResult[i,1]=(string)myDataSet.Tables[0].Rows[i].ItemArray[1];
                }

                return strResult;        
            }
            else
                return null;
        }

        #endregion


        自定义的自动转换某表的所有列成为中文名的过程#region 自定义的自动转换某表的所有列成为中文名的过程
        //在数组中查找是否存指定的内容,如果不存在,则返回-1,否则返回相应的下标索引
        public static int FindInArray(string[,] ColText,string ColName)
        {
            for (int i = 0; i < ColText.Length / 2; i++)
            {
                if (ColText[i,0].ToString().ToUpper() == ColName.ToUpper())
                    return i;
            }
            return -1;
        }

        private static void SetColText(DataTable dt,DataGrid dg,string [,] coltext)
        {
            //定义新的TableStyle
            DataGridTableStyle dgs    =new DataGridTableStyle();
            dgs.MappingName            =dt.TableName;

            //循环取出每列的列名
            for (int i = 0 ; i < dt.Columns.Count ; i++)
            { 
                string sFieldName    = dt.Columns[i].ColumnName;         //取出英文列名
                int        iIndex        = FindInArray(coltext,sFieldName);    //判断是否存在中文描述

                DataGridColumnStyle captioncol    = new DataGridTextBoxColumn();
                captioncol.MappingName            = sFieldName;            //原字段

                //如果存在中文列名的话,则转换后加入到GridColumnStyles中;否则保持原英文字段名
                if (iIndex >= 0)
                     captioncol.HeaderText = coltext[iIndex,1];    //中文描述
                else captioncol.HeaderText = sFieldName;

                dgs.GridColumnStyles.Add(captioncol);
            }
            //把转换后的TableStyle保存到表格中去
            dg.TableStyles.Clear();
            dg.TableStyles.Add(dgs);
        }
        #endregion


        自定义 ErrorBox InformationBox QuestionBox 对话框#region 自定义 ErrorBox InformationBox QuestionBox 对话框
//        public static void MsgBox(string text,string caption,MessageBoxButtons buttons,MessageBoxIcon icon,MessageBoxDefaultButton defaultButton)
        public static void ErrorBox(string text)
        {
            MessageBox.Show(text,"错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
        }

        public static void InformationBox(string text)
        {
            MessageBox.Show(text,"信息",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        public static DialogResult QuestionBox(string text)
        {
            return MessageBox.Show(text,"询问",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2);
        }

        #endregion


        条件判断函数 iif#region 条件判断函数 iif
        public static string iif (bool bBool,string sValue1,string sValue2)
        { 
            if (bBool==true) return sValue1;
            else             return sValue2;
        }
        #endregion


        返回指定的表格总共有多少行#region 返回指定的表格总共有多少行
        /** <summary>
        /// 返回指定的表格总共有多少行
        /// </summary>
        /// <param name="myGrid">要判断的表格名称</param>
        /// <returns>表格内容的实际行数(不包括标题行)</returns>
        public static int GetGridRowsCount(DataGrid myGrid)
        {
            int i;
            int iIndex = myGrid.CurrentRowIndex;

            myGrid.BeginInit();
            for (i = 0; i < 1000; i++)
            {
                try
                {
                    myGrid.CurrentCell = new DataGridCell(i,0);
                    if (myGrid.CurrentCell.RowNumber != i) break;
                }
                catch
                {
                    MyClass.ErrorBox(" eror ");
                    break;
                }
            }
            myGrid.CurrentRowIndex = iIndex;
            myGrid.EndInit();
            return i;
        }
        #endregion


        加密解密过程 Encrypt Decrypt#region 加密解密过程 Encrypt Decrypt

        /** <summary>
        /// 加密字符串
        /// 最长15位的原文,加密后形成24位的密文
        /// </summary>
        /// <param name="str">要加密的原文</param>
        /// <returns>加密后的密文</returns>
        public static string Encrypt(string str)
        {
            try
            {
                return MyEncrypt.Encrypt3DES(str,MYKEY);
            }
            catch (Exception e)
            {
                ErrorBox("加密过程出错,错误原因如下:" + (char)13 + (char)13 + e.Message);
                return "";
            }
        }


        /** <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="str">要解密的密文</param>
        /// <returns>解密后的明文</returns>
        public static string Decrypt(string str)
        {
            try
            {
                return MyEncrypt.Decrypt3DES(str,MYKEY);
            }
            catch (Exception e)
            {
                ErrorBox("解密过程出错,错误原因如下:" + (char)13 + (char)13 + e.Message);
                return "";
            }
        }
        #endregion

        
        对ini文件进行写操作的函数#region 对ini文件进行写操作的函数
        public static void IniWriteValue(string Section,string Key,string Value,string filepath)
        {
            WritePrivateProfileString(Section,Key,Value,filepath);
        }
        #endregion
        
        
        对ini文件进行读操作的函数#region 对ini文件进行读操作的函数
        public static string IniReadValue(string Section,string Key,string filepath)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section,Key,"",temp, 255, filepath);
            return temp.ToString();
        }
        #endregion


        生成连接字符串#region 生成连接字符串
        public static void MakeConnectString()
        {
            //取得应用程序名及路径
            string path    = Application.ExecutablePath;
            //生成与应用程序同名的INI文件名
            string IniFile = Regex.Replace(path,".exe",".ini");
            //读取INI文件中的配置
            string m_Server = IniReadValue("Database","Server",IniFile);
            if (m_Server == "")  m_Server = "(local)";
            //生成连接字符串
            CONN_STR        = "server=" + m_Server + ";database=" + DATABASE + ";uid=" + UID + ";pwd=" + PWD;
        }
        #endregion

    
    }


    自定义的加密类#region 自定义的加密类
    /** <summary>
    /// 自定义的加密类
    /// </summary>
    public class MyEncrypt
    {
        /** <summary>
        /// md5加密指定字符串
        /// </summary>
        /// <param name="a_strValue">要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string EncryptMD5String(string a_strValue)
        {
            //DEBUG
            #if DEBUG
                Debug.Assert(a_strValue.Trim() != "" , "空字符串" , "空字符串不需要加密") ;
            #endif
            //转换成bytearray
            Byte[] hba = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(StringToByteArray(a_strValue));
            return ByteArrayToString(hba) ;
        }

        /** <summary>
        /// 判断两个加密字符串是否相同
        /// </summary>
        /// <param name="a_str1"></param>
        /// <param name="a_str2"></param>
        /// <returns>如果相同返回真</returns>
        public static bool IsSame(string a_str1 , string a_str2)
        {
            Byte[] b1 = StringToByteArray(a_str1) ;
            Byte[] b2 = StringToByteArray(a_str2) ;
            if (b1.Length != b2.Length)
            {
                return false;
            }

            for (int i = 0 ; i < b1.Length ; i ++)
            {
                if(b1[i] != b2[i])
                {
                    return false ;
                }
            }
            return true ;
        }

        /** <summary>
        /// 转换string到Byte树组
        /// </summary>
        /// <param name="s">要转换的字符串</param>
        /// <returns>转换的Byte数组</returns>
        public static Byte[] StringToByteArray(String s)
        {
            return Encoding.UTF8.GetBytes(s) ;
        }

        /** <summary>
        /// 转换Byte数组到字符串
        /// </summary>
        /// <param name="a_arrByte">Byte数组</param>
        /// <returns>字符串</returns>
        public static string ByteArrayToString(Byte[] a_arrByte)
        {
            return Encoding.UTF8.GetString(a_arrByte) ;
        }

        /** <summary>
        /// 3des加密字符串
        /// </summary>
        /// <param name="a_strString">要加密的字符串</param>
        /// <param name="a_strKey">密钥</param>
        /// <returns>加密后并经base64编码的字符串</returns>
        /// <remarks>静态方法,采用默认ascii编码</remarks>
        public static string Encrypt3DES(string a_strString, string a_strKey) 
        {
            TripleDESCryptoServiceProvider DES = new
                TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(a_strKey));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(a_strString);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock
                (Buffer, 0, Buffer.Length));
        }//end method

        /** <summary>
        /// 3des加密字符串
        /// </summary>
        /// <param name="a_strString">要加密的字符串</param>
        /// <param name="a_strKey">密钥</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>加密后并经base63编码的字符串</returns>
        /// <remarks>重载,指定编码方式</remarks>
        public static string Encrypt3DES(string a_strString, string a_strKey , Encoding encoding) 
        {
            TripleDESCryptoServiceProvider    DES        = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider        hashMD5 = new MD5CryptoServiceProvider();

            DES.Key     = hashMD5.ComputeHash(encoding.GetBytes(a_strKey));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            byte[] Buffer = encoding.GetBytes(a_strString);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }


        /** <summary>
        /// 3des解密字符串
        /// </summary>
        /// <param name="a_strString">要解密的字符串</param>
        /// <param name="a_strKey">密钥</param>
        /// <returns>解密后的字符串</returns>
        /// <exception cref="">密钥错误</exception>
        /// <remarks>静态方法,采用默认ascii编码</remarks>
        public static string Decrypt3DES(string a_strString, string a_strKey)
        {
            TripleDESCryptoServiceProvider  DES        = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider        hashMD5 = new MD5CryptoServiceProvider();

            DES.Key  = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(a_strKey));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESDecrypt = DES.CreateDecryptor();

            string result = "";
            try
            {
                byte[] Buffer    = Convert.FromBase64String(a_strString);
                result            = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch(Exception e)
            {
                #if DEBUG
                    Console.WriteLine("错误:{0}" , e) ;
                #endif//DEBUG
                throw ( new Exception("Invalid Key or input string is not a valid base64 string" , e)) ;
            }
            return result ;
        }//end method

        /** <summary>
        /// 3des解密字符串
        /// </summary>
        /// <param name="a_strString">要解密的字符串</param>
        /// <param name="a_strKey">密钥</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>解密后的字符串</returns>
        /// <exception cref="">密钥错误</exception>
        /// <remarks>静态方法,指定编码方式</remarks>
        public static string Decrypt3DES(string a_strString, string a_strKey , Encoding encoding)
        {
            TripleDESCryptoServiceProvider    DES        = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider        hashMD5 = new MD5CryptoServiceProvider();

            DES.Key        = hashMD5.ComputeHash(encoding.GetBytes(a_strKey));
            DES.Mode    = CipherMode.ECB;

            ICryptoTransform DESDecrypt = DES.CreateDecryptor();

            string result = "";
            try
            {
                byte[] Buffer = Convert.FromBase64String(a_strString);
                result          = encoding.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch(Exception e)
            {
                #if DEBUG
                    Console.WriteLine("错误:{0}" , e) ;
                #endif//DEBUG
                
                throw( new Exception("Invalid Key or input string is not a valid base64 string" , e)) ;
            }

            return result ;
        }//end method

    }


    #endregion


    一个公共数据库连接类#region 一个公共数据库连接类
    public class C_Connection
    {
        private static System.Data.SqlClient.SqlConnection conn = null;
        
        private C_Connection()
        {
        }

        public static System.Data.SqlClient.SqlConnection Connection
        {
            get
            {
                if (conn==null)
                    conn=new System.Data.SqlClient.SqlConnection(MyClass.CONN_STR);
                return conn;
            }
        }
    }
    #endregion

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值