C#底层库--数据库访问帮助类(MySQL版)

系列文章

C#底层库–记录日志帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124187709

C#底层库–数据库访问帮助类(MySQL版)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379

C#底层库–获取文件版本和MD5值
本文链接:https://blog.csdn.net/youcheng_ge/article/details/112513871

C#底层库–操作文件帮助类FileHelper(获取目录的所有文件)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887161

C#底层库–操作Excel帮助类(读取、导出表格)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887445

C#底层库–软件版本管理XML
本文链接:https://blog.csdn.net/youcheng_ge/article/details/110195766

C#RegexHelper正则表达式帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/109745286


文章目录

  • 系列文章
  • 前言
  • 一、底层库介绍
  • 二、底层库源码
  • 三、调用方法


前言

本文将新增一个专栏–底层库,分享编程过程中常用的方法函数。我们将这些常用的方法函数,进行封装,反复测试,形成通用化类库。
方便研发人员,只需要几行代码就可以使用它,解决一些难点问题。
底层库的封装涉及到:数据库操作、加解密算法、日志记录、网络通信、邮件发送、文件操作、参数保存、Excel导入导出等等,持续关注本专栏吧。大家有任何问题,也可以评论区反馈,私信我。

一、底层库介绍

数据库访问帮助类,包含执行脚本、含参执行脚本、执行存储过程、事务处理。

二、底层库源码

创建类MySQLHelper.cs

using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Collections.Generic;

namespace QRCodeProduce
{
    /// 
    /// 数据访问抽象基础类
    /// 
    public abstract class MySQLHelper
    {
        //简单工厂模式:将类抽象化处理,编写工厂方法,将客户传入参数转换为对应的实例对象。
        public static string server = "";
        public static string port = "";
        public static string uid = "";
        public static string pwd = "";
        public static string BaseName = "";

        public static string connectionString
        {
            get
            {
                return $"server={server};uid={uid};pwd={pwd};database={BaseName};SslMode=None;charset=utf8";
            }
        }

        /// 
        /// 构造函数
        /// 
        public MySQLHelper()
        {
        }

        #region 公用方法
        public static bool Test()
        {
            string l_strSQL = "select 1 ";
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(l_strSQL, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    catch (MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }



        /// 
        /// 查询表是否存在
        /// 
        /// 表名
        /// bool
        public static bool Exists(string strTableName)
        {
            string l_strSQL = "select 1 1 from " + strTableName;
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(l_strSQL, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    catch (MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// 
        /// 查询数据是否存在,带参数
        /// 
        /// 查询语句
        /// 参数列表
        /// 
        public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(strSql, connection))
                {
                    cmd.Parameters.AddRange(cmdParms);
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    catch (MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }


        /// 
        /// 获取表中字段的最大值
        /// 
        /// 列名
        /// 表名
        /// 
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(strsql, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return 1;
                        }
                        else
                        {
                            return int.Parse(obj.ToString()); ;
                        }
                    }
                    catch (MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// 
        /// 执行查询语句,无参数,返回DataSet
        /// 
        /// 查询语句
        /// DataSet
        public static DataSet ShowDataBases(string SQLString)
        {
            string l_str = $"server={server};uid={uid};pwd={pwd};SslMode=None;";
            using (MySqlConnection connection = new MySqlConnection(l_str))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (MySqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
        #endregion


        #region  执行简单SQL语句
        /// 
        /// 执行SQL语句,返回影响的记录数
        /// 
        /// SQL语句
        /// 影响的记录数
        public static int ExecuteSql(string SQLString)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// 
        /// 执行SQL语句(带特殊文本),返回影响的记录数
        /// 
        /// SQL语句
        /// 参数内容
        /// 影响的记录数
        public static int ExecuteSql(string SQLString, string strParamText)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand(SQLString, connection);
                MySqlParameter myParameter = new MySqlParameter("@content", SqlDbType.NText);
                myParameter.Value = strParamText;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (MySqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// 
        /// 执行SQL语句(带参数),返回影响的记录数
        /// 
        /// SQL语句
        /// 准备好的参数列表
        /// 影响的记录数
        public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (MySqlException e)
                    {
                        throw e;
                    }
                }
            }
        }



        /// 
        /// 指定时间执行,返回影响行数
        /// 
        /// 执行语句
        /// 指定时间
        /// 影响的记录数
        public static int ExecuteSqlByTime(string SQLString, int Times)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (MySqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }


        /// 
        /// 批量执行SQL语句,实现数据库事务,返回执行行数。
        /// 
        /// 多条SQL语句		
        public static int ExecuteSqlTran(List<String> SQLTextList)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                MySqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLTextList.Count; n++)
                    {
                        string strsql = SQLTextList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }

        /// 
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// 
        /// SQL语句
        /// 图像字节,数据库的字段类型为image的情况
        /// 影响的记录数
        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand(strSQL, connection);
                MySqlParameter myParameter = new MySqlParameter("@fs", SqlDbType.Image);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (MySqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }


        //执行单条插入语句,并返回id,不需要返回id的用ExceuteNonQuery执行。
        /// 
        /// 执行插入语句并返回Id,不需返回Id的用其它执行方法
        /// 
        /// Sql语句
        /// 此参数为Null时进行
        /// 
        public static int ExecuteInsert(string strSql, MySqlParameter[] parameters)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand(strSql, connection);
                try
                {
                    connection.Open();
                    if (parameters != null) cmd.Parameters.AddRange(parameters);
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = @"select LAST_INSERT_ID()";
                    //此方法估计也可直接用  select   @@identity 获得,两值基本都是全局服务,使用时不能关闭Connection
                    int value = Int32.Parse(cmd.ExecuteScalar().ToString());
                    return value;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        /// 
        /// 无参查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
        /// 
        /// 查询语句
        /// MySqlDataReader
        public static MySqlDataReader ExecuteReader(string strSqlText)
        {
            MySqlConnection conn = new MySqlConnection(connectionString);
            MySqlCommand cmd = new MySqlCommand(strSqlText, conn);
            try
            {
                conn.Open();
                MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (MySqlException e)
            {
                throw e;
            }
        }

        /// 
        ///  带参查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
        /// 
        /// 查询语句
        /// 参数列表
        /// MySqlDataReader
        public static MySqlDataReader ExecuteReader(string strSqlText, params MySqlParameter[] cmdParas)
        {
            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand cmd = new MySqlCommand();
            try
            {
                PrepareCommand(cmd, connection, null, strSqlText, cmdParas);
                MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);//不加using,执行conn关闭后自动关闭Reader
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (MySqlException e)
            {
                throw e;
            }
        }

        /// 
        /// 执行查询语句,无参数,返回DataSet
        /// 
        /// 查询语句
        /// DataSet
        public static DataSet Query(string SQLString)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (MySqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        /// 
        /// 执行语句,返回DataSet
        /// 
        /// Sql语句
        /// 执行时间
        /// 
        public static DataSet Query(string SQLString, int Times)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (MySqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
        /// 
        /// 带参查询语句,返回DataSet
        /// 
        /// 查询语句
        /// 参数列表
        /// DataSet
        public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }




        /// 
        /// 准备命令语句
        /// 
        /// Command命令
        /// Connection对象
        /// 是否是事务
        /// 语句
        /// 参数列表
        private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (MySqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 参数转换
        /// 
        /// 准备MysqlCommad参数
        /// 
        /// MySqlCommand cmd对象
        /// MySqlConnection conn对象
        /// 数据库事务
        /// text or StoredProcedure
        /// 存储过程名
        /// SqlCommand的参数
        private static void PrepareMySqlCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, MySqlParameter[] cmdParms)
        {
            //连接状态是否打开
            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            //Transact-SQL 事务
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = cmdType;
            if (cmdParms != null)
            {
                foreach (MySqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        /// 
        /// 放回一个MakeMySqlParameter
        /// 
        /// 参数名字
        /// 参数类型
        /// 参数大小
        /// 参数值
        /// SQLiteParameter的值
        public static MySqlParameter MakeMySqlParameter(string name, MySqlDbType type, int size, object value)
        {
            MySqlParameter parm = new MySqlParameter(name, type, size);
            parm.Value = value;
            return parm;
        }
        /// 
        /// 创建MysqlParameter
        /// 
        /// 字段名称
        /// 数据类型
        /// 字段值
        /// 返回类型为MySqlParameter
        public static MySqlParameter MakeMySqlParameter(string name, MySqlDbType type, object value)
        {
            MySqlParameter parm = new MySqlParameter(name, type);
            parm.Value = value;
            return parm;
        }
        #endregion

        #region 存储过程的调用
        /// 
        /// 无参存储过程,用于插入修改删除表数据,无返回值
        /// 
        /// 存储过程脚本
        public static void ExecuteProc(string ProcText)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(ProcText, connection))
                {
                    try
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        connection.Open();
                        cmd.ExecuteScalar();
                    }
                    catch (MySqlException e)
                    {
                        connection.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }


        /// 
        /// 带参存储过程,无返回值
        /// 
        /// 存储过程脚本
        /// 参数MySqlParameter[] cmdParms
        public static void ExecuteProc(string ProcText, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    try
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        PrepareMySqlCommand(cmd, connection, null, CommandType.StoredProcedure, ProcText, cmdParms);
                        cmd.ExecuteScalar();
                    }
                    catch (MySqlException e)
                    {
                        connection.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }
        /// 
        /// 无参存储过程,返回DataSet
        /// 
        /// 存储过程脚本
        /// 返回DataSet
        public static DataSet ExecuteProcDataset(string ProcText)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand();
                PrepareMySqlCommand(cmd, connection, null, CommandType.StoredProcedure, ProcText, null);
                using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }

        /// 
        /// 带参存储过程,返回DataSet
        /// 
        /// 存储过程名
        /// 参数MySqlParameter[] cmdParms
        /// 返回DataSet
        public static DataSet ExecuteProcDataset(string ProcText, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand();
                PrepareMySqlCommand(cmd, connection, null, CommandType.StoredProcedure, ProcText, cmdParms);
                using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (MySqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }
        #endregion
   
        #endregion
    }
}

三、调用方法

                MySQLHelper.server = AppConfig.GetValue("db_server");
                MySQLHelper.port = AppConfig.GetValue("db_port");
                MySQLHelper.BaseName = AppConfig.GetValue("db_base");
                MySQLHelper.uid = AppConfig.GetValue("db_uid");
                MySQLHelper.pwd = AppConfig.GetValue("db_pwd");

                string l_strSql = $"UPDATE t300_muxianzhiliang_result SET 原料编号='{baseDataInput_原料编号.StringValue}'," +
                    $"原料规格='{baseDataInput_原料规格.StringValue}',原料强度='{baseDataInput_原料强度.StringValue}'," +
                    $"黄丝厂家='{baseDataInput_黄丝厂家.StringValue}',黄丝代码='{baseDataInput_黄丝代码.StringValue}',doff='{baseDataInput_doff.StringValue}'  WHERE id= {m_strkeyVaule}";

                MySQLHelper.ExecuteSql(l_strSql);

程序运行效果:
C#底层库--数据库访问帮助类(MySQL版)_第1张图片

你可能感兴趣的:(数据库,底层库(工具,通用类),c#,数据库,mysql)