码迷,mamicode.com
首页 > 数据库 > 详细

MySql数据库连接操作

时间:2015-07-27 18:09:05      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

主要封装为MySqlHelper类

namespace CiWong.LearningLevelApi.MySqlHelp
{
    /// <summary>
    /// MySqlHelper 类是基于.net框架开发的数据库操作类
    /// </summary>
    public class MySqlHelper
    {
        #region 缓存Hashtable
        // 存储缓存参数的Hashtable
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
        #endregion

        #region 重载+1 获取连接字符串
        /// <summary>
        /// 重载+1 获取连接字符串 [GetStrCon()]
        /// </summary>
        /// <returns>连接字符串(如果配置文件中无[SQL]名称的连接字符串,则抛出异常)</returns>
        public static string GetStrCon()
        {
            try
            {
                string CONN_STRING = ConfigurationManager.ConnectionStrings["QuesContext"].ConnectionString;
                return CONN_STRING;
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("配置文件中没有[SQL]名称的connectionStrings!错误原因:{0}", ex.ToString()));
                throw;
            }
        }
        #endregion

        #region 重载+2 获取连接字符串
        /// <summary>
        /// 重载+2 获取连接字符串 [GetStrCon(string strConfig)]
        ///     如果配置文件中有strConfig为名称的连接字符串,则
        ///         获取它的内容
        ///     如果没有,则默认strConfig为连接字符串
        /// </summary>
        /// <param name="strConfig">配置文件中连接字符串的名称</param>
        /// <returns>连接字符串</returns>
        public static string GetStrCon(string strConfig)
        {
            string CONN_STRING = string.Empty;
            if (ConfigurationManager.ConnectionStrings[strConfig] != null)
                CONN_STRING = ConfigurationManager.ConnectionStrings[strConfig].ConnectionString;
            else
                CONN_STRING = strConfig;
            return CONN_STRING;
        }
        #endregion

        #region 重载+1 创建连接对象 [GetConn()]
        /// <summary>
        /// 重载+1 返回 conn连接对象 [GetConn()]
        /// </summary>
        /// <returns> MySqlConnection </returns>
        public static MySqlConnection GetConn()
        {
            try
            {
                return new MySqlConnection(GetStrCon());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 重载+2 创建连接对象 [GetConn()]
        /// <summary>
        /// 重载+2 返回 conn连接对象 [GetConn()]
        ///     如果配置文件中有strConfig名称的连拉字符串,则
        ///         获取它的内容
        ///     如果没有,则默认strConfig为连接字符串
        /// </summary>
        /// <param name="strConfig">配置文件中连接字符串的名称</param>
        /// <returns> MySqlConnection </returns>
        public static MySqlConnection GetConn(string strConfig)
        {
            try
            {
                return new MySqlConnection(GetStrCon(strConfig));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 关闭连接[CloseConn(...)]
        /// <summary>
        /// 关闭 conn连接对象
        /// </summary>
        /// <param name="conn">连接对象</param>
        public static void CloseConn(MySqlConnection conn)
        {
            if (conn.State != ConnectionState.Closed)
                conn.Close();
        }
        #endregion

        #region 清空与指定连接相关的连接池
        /// <summary>
        /// 清空与指定连接相关的连接池 [ClosePool(MySqlConnection conn)]
        /// </summary>
        public static void ClosePool(MySqlConnection conn)
        {
            MySqlConnection.ClearPool(conn);
        }
        #endregion

        #region 清空所有连接池
        /// <summary>
        /// 清空所有连接池 [ClosePool()]
        /// </summary>
        public static void ClosePool()
        {
            MySqlConnection.ClearAllPools();
        }
        #endregion

        #region 返回MySqlCommand对象[GetCmd(...)]
        /// <summary>
        /// 返回MySqlCommand对象
        /// </summary>
        /// <param name="conn">conn 连接对象</param>
        /// <param name="trans">事物对象</param>
        /// <param name="cmdType">SQL 执行的类型</param>
        /// <param name="cmdText">SQL	执行语句</param>
        /// <param name="cmdParms">MySqlParameter[] 对象</param>
        /// <returns> 返回comm 对象</returns>
        public static MySqlCommand GetCmd(MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;

                if (trans != null)
                    cmd.Transaction = trans;

                if (cmdParms != null)
                {
                    foreach (MySqlParameter parm in cmdParms)
                        cmd.Parameters.Add(parm);
                }

                return cmd;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 重载+1 通过连接字符串,执行SqlCommand(不返回结果集)[ExecuteNonQuery(...)]
        /// <summary>
        /// 重载+1 通过连接字符串,执行SqlCommand(不返回结果集)
        /// 利用提供的参数值		
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connString">为MySqlConnection对象提供:一个有效的连接字符串</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>
        /// <returns>执行命令受影响的记录条数</returns>
        public static int ExecuteNonQuery(string connString, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand();

                using (MySqlConnection conn = new MySqlConnection(connString))
                {
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                    int val = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    return val;
                }
            }
            catch (Exception ex)
            {
                //引发异常,没有记录受影响
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 重载+2 通过存在的MySqlConnection对象,执行MySqlCommand(不返回结果集)[ExecuteNonQuery(...)]
        /// <summary>
        /// 重载+2 通过存在的MySqlConnection对象,执行MySqlCommand(不返回结果集)
        /// 利用提供的参数值	
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个已经存在的SqlConnection对象</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>
        /// <returns>执行命令受影响的记录条数</returns>
        public static int ExecuteNonQuery(MySqlConnection conn, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand();

                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                cmd.Dispose();
                return val;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                //引发异常,没有记录受影响
                throw;
            }
            finally
            {
                conn.Close();
            }
        }
        #endregion

        #region 重载+3  通过存在的 MySqlTransaction,执行MySqlCommand(不返回结果集)[ExecuteNonQuery(...)]
        /// <summary>
        /// 重载+3  通过存在的 MySqlTransaction,执行MySqlCommand(不返回结果集)
        /// 利用提供的参数值		
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>		
        /// <param name="trans">一个已经存在的 trans</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>
        /// <returns>执行命令受影响的记录条数</returns>
        public static int ExecuteNonQuery(MySqlTransaction trans, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand();

                PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                cmd.Dispose();
                return val;
            }
            catch (Exception ex)
            {
                //引发异常,没有记录受影响
                Console.WriteLine(ex.ToString());
                throw;
            }
            finally
            {
                trans.Connection.Close();
            }
        }
        #endregion

        #region 重载+1 通过连接字符串,执行MySqlCommand(返回结果集)  [ExecuteDataSet(...)]
        /// <summary>
        /// 重载+1 通过连接字符串,执行MySqlCommand(返回结果集)
        /// 利用提供的参数值		
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataSet(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connString">为MySqlConnection对象提供:一个有效的连接字符串</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>
        /// <returns>返回一个结果集:DataSet对象</returns>
        public static DataSet ExecuteDataSet(string connString, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            DataSet ds = new DataSet();
            //使用一个异常,如果发生异常,则将连接关闭	
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connString))
                {
                    MySqlCommand cmd = new MySqlCommand();
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                    MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                    adp.Fill(ds);
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    return ds;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 重载+2 通过已经存在的MySqlConnection对象,执行MySqlCommand(返回结果集)  [ExecuteDataSet(...)]
        /// <summary>
        /// 重载+2 通过已经存在的MySqlConnection对象,执行MySqlCommand(返回结果集)
        /// 利用提供的参数值		
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  DataSet ds = ExecuteDataSet(conn, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个已经存在的MySqlConnection对象</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>
        /// <returns>返回一个结果集:DataSet对象</returns>
        public static DataSet ExecuteDataSet(MySqlConnection conn, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            DataSet ds = new DataSet();
            //使用一个异常,如果发生异常,则将连接关闭	
            try
            {
                MySqlCommand cmd = new MySqlCommand();
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                adp.Fill(ds);
                cmd.Parameters.Clear();
                cmd.Dispose();
                return ds;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
            finally
            {
                conn.Close();
            }
        }
        #endregion

        #region 重载+1 通过连接字符串,执行MySqlCommand(返回结果集的一个MySqlDataReader对象)[ExecuteReader(...)]
        /// <summary>
        /// 重载+1 通过连接字符串,执行MySqlCommand(返回结果集的一个MySqlDataReader对象)
        /// 利用提供的参数值		
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  MySqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connString">为MySqlConnection对象提供:一个有效的连接字符串</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>	
        /// <returns>包含结果集的一个:MySqlDataReader对象</returns>
        public static MySqlDataReader ExecuteReader(string connString, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            MySqlConnection conn = new MySqlConnection(connString);

            //使用一个异常,如果发生异常,则将连接关闭			
            try
            {
                MySqlCommand cmd = new MySqlCommand();
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                cmd.Dispose();
                return rdr;
            }
            catch (Exception ex)
            {
                CloseConn(conn);
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 重载+2 通过已经存在的MySqlConnection对象,执行MySqlCommand(返回结果集的一个MySqlDataReader对象) [ExecuteReader(...)]
        /// <summary>
        /// 重载+2 通过已经存在的MySqlConnection对象,执行MySqlCommand(返回结果集的一个MySqlDataReader对象)
        /// 利用提供的参数值		
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  MySqlDataReader r = ExecuteReader(conn, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个已经存在的SqlConnection对象</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>			
        /// <returns>包含结果集的一个:MySqlDataReader对象</returns>
        public static MySqlDataReader ExecuteReader(MySqlConnection conn, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            //使用一个异常,如果发生异常,则将连接关闭	
            try
            {
                MySqlCommand cmd = new MySqlCommand();
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                cmd.Dispose();
                return rdr;
            }
            catch (Exception ex)
            {
                CloseConn(conn);
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 重载+1 通过连接字符串,执行MySqlCommand [ExecuteScalar(...)]
        /// <summary>
        /// 重载+1 通过连接字符串,执行MySqlCommand(返回第一条记录的第一列的值,一般是返回汇总值等;如:select max(id) from userTab)
        /// 利用提供的参数值				
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connString">为MySqlConnection对象提供:一个有效的连接字符串</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>	
        /// <returns>返回一个对象:如果要使用具体的值,需要使用Convert.To{Type}进行转换</returns>
        public static object ExecuteScalar(string connString, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand();

                using (MySqlConnection conn = new MySqlConnection(connString))
                {
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                    object val = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    return val;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 重载+2 通过已经存在的MySqlConnection对象,执行MySqlCommand [ExecuteScalar(...)]
        /// <summary>
        /// 重载+2 通过已经存在的MySqlConnection对象,执行MySqlCommand(返回第一条记录的第一列的值,一般是返回汇总值等;如:Select max(ColumnName) From TableName)
        /// 利用提供的参数值	
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(conn, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个已经存在的SqlConnection对象</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本</param>
        /// <param name="cmdParms">执行命令的参数列表</param>
        /// <returns>返回一个对象:如果要使用具体的值,需要使用Convert.To{Type}进行转换</returns>
        public static object ExecuteScalar(MySqlConnection conn, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand();

                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                cmd.Dispose();
                return val;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
            finally
            {
                CloseConn(conn);
            }
        }
        #endregion

        #region 将参数数组增加至Hashtable,缓存在缓冲区 [CacheParameters(...)]
        /// <summary>
        /// 存储:将参数数组增加至缓冲区		
        /// </summary>
        /// <param name="cacheKey">缓冲区参数的键名</param>
        /// <param name="cmdParms">缓冲区对应键名的参数值</param>
        public static void CacheParameters(string cacheKey, params MySqlParameter[] cmdParms)
        {
            parmCache[cacheKey] = cmdParms;
        }
        #endregion

        #region 从缓冲区得到Hashtable中的参数列表的值 [GetCachedParameters(...)]
        /// <summary>
        /// 检索值:得到缓冲区中的参数列表值
        /// </summary>
        /// <param name="cacheKey">缓冲区参数的键名</param>
        /// <returns>缓冲区对应键名的参数值</returns>
        public static MySqlParameter[] GetCachedParameters(string cacheKey)
        {
            //获取 key 为cachekey 的值 parmCache[参数化SQL语句]=parameter[]数据组对象
            MySqlParameter[] cachedParms = (MySqlParameter[])parmCache[cacheKey];

            //如果不存在 则返回为空
            if (cachedParms == null)
                return null;
            //反之 Hashtable表中存在 key为cacheky 的对象则返回 他的 副本 对象 par[]
            MySqlParameter[] clonedParms = new MySqlParameter[cachedParms.Length];

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

            return clonedParms;
        }
        #endregion

        #region 执行预定义Command对象[PrepareCommand(...)]
        /// <summary>
        /// 要执行:预定义Command对象(PrepareCommand)
        /// </summary>
        /// <param name="cmd">MySqlCommand 对象</param>
        /// <param name="conn">MySqlConnection 对象</param>
        /// <param name="trans">MySqlTransaction 对象</param>
        /// <param name="cmdType">命令类别:存储过程、文本字符串等</param>
        /// <param name="cmdText">存储过程名称或SQL命令文本,如:select * from UserTab</param>		
        /// <param name="cmdParms">Command对象需要使用的参数列表</param>
        public static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, MySqlParameter[] cmdParms)
        {
            try
            {
                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 (MySqlParameter parm in cmdParms)
                        cmd.Parameters.Add(parm);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        #endregion

        #region 提交事务 [TransactionCommit(...)]
        /// <summary>
        /// 提交事务
        /// </summary>
        /// <param name="trans">事务</param>
        public static void TransactionCommit(MySqlTransaction trans)
        {
            trans.Commit();
        }
        #endregion

        #region 回滚事务 [TransactionRollback(...)]
        /// <summary>
        /// 回滚事务
        /// </summary>
        /// <param name="trans">事务</param>
        public static void TransactionRollback(MySqlTransaction trans)
        {
            trans.Rollback();
        }
        #endregion
    }
}

  

MySql数据库连接操作

标签:

原文地址:http://www.cnblogs.com/Aamir-Ye/p/4680777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!