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


    系列文章

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

    C#底层库–MySQL数据库访问操作辅助类(推荐阅读)
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379

    C#底层库–XML配置参数读写辅助类(推荐阅读)
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/129175304

    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#底层库–随机数生成
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/126888812

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

    C#底层库–CSV和DataTable相互转换
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/128804367

    C#底层库–Image图片操作类
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298

    C#底层库–JSON帮助类_详细(序列化、反序列化、list、datatable)
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805705

    C#底层库–cookie操作辅助类
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816347

    C#底层库–Session操作辅助类
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/128817096

    C#底层库–数据实体类
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816638

    C#底层库–Image图片操作类
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298

    C#底层库–数据库类型与程序类型转换类
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/128817610

    C#底层库–日期扩展类(上周、本周、明年、前年等)
    本文链接:https://blog.csdn.net/youcheng_ge/article/details/129040663



    前言

    本专栏为【底层库】,主要介绍编程过程中 通用函数。我们将这些通用固化的源码,进行重写、封装、拓展,再进行单元测试、集成测试、beta测试,最终形成通用化模板,这里我们称为“底层库”。

    作为研发人员的你,并不需要花大量时间,研究“底层库”的含义,及“底层库”的实现方法。你只需要几行调用代码,就可以解决项目上碰到的难题。而底层库使用方法,本专栏均有详细介绍,也有项目应用场景。

    底层库已实现功能:MySQL脚本构建器、MySQL数据库访问操作、参数配置文件读写、加解密算法、日志记录、HTTP通信、Socket通信、API前后端交互、邮件发送、文件操作、配置参数存储、Excel导入导出、CSV和DataTable转换、压缩解压、自动编号、Session操作等。

    本专栏会持续更新,不断优化【底层库】,大家有任何问题,可以私信我,如果你对本栏感兴趣,欢迎关注,我将带你用最简洁的代码实现复杂的功能。

    一、底层库介绍

    本文主要介绍数据库访问操作类,包含:SQL插入脚本、SQL查询脚本、数据库表是否存在判断、带参脚本执行、包含事务回滚脚本执行、存储过程脚本等等。
    注意:其中本文中程序源码,使用到《C#底层库--XML参数配置文件读写类》,不清楚的可以找一下专栏文章。

    二、底层库源码

    2.1 程序源码

    建类MySQLHelper.cs

    using System;
    using System.Data;
    using MySql.Data.MySqlClient;
    using System.Collections.Generic;
    
    namespace YS_Server
    {
        /// 
        /// 数据访问抽象基础类
        /// 
        public class MySQLHelper
        {
            //简单工厂模式:将类抽象化处理,编写工厂方法,将客户传入参数转换为对应的实例对象。
            public string server { get; set; }
            public string port { get; set; }
            public string uid { get; set; }
            public string pwd { get; set; }
            public string BaseName { get; set; }
            public string connectionString { get; set; }
    
            /// 
            /// 构造函数
            /// 
            public MySQLHelper()
            {
                this.server = AppConfig.GetValue("db_server");
                this.port = AppConfig.GetValue("db_port");
                this.BaseName = AppConfig.GetValue("db_base");
                this.uid = AppConfig.GetValue("db_uid");
                this.pwd = AppConfig.GetValue("db_pwd");
                //MySQL.Data 8.0.28.0
                //this.connectionString = $"server={server};port={port};user id={uid};password={pwd};database={BaseName};pooling=true;ConnectionTimeout=1800;CharSet=utf8";
                //MySQL.Data 8.0.26.0
                this.connectionString = $"server={server};port={port};uid={uid};pwd={pwd};database={BaseName};SslMode=None;Charset=utf8";
            }
    
            /// 
            /// 构造函数
            /// 
            public MySQLHelper(string server, string port, string uid, string pwd, string BaseName)
            {
                this.server = server;
                this.port = port;
                this.BaseName = BaseName;
                this.uid = uid;
                this.pwd = pwd;
    
                this.connectionString = $"server={server};uid={uid};pwd={pwd};database={BaseName};SslMode=None;charset=utf8";
            }
    
            #region 公用方法
            public 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 bool Exists(string strTableName)
            {
                string l_strSQL = "SHOW TABLES LIKE '" + 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 MySqlParameter MakeMySqlParameter(string name, MySqlDbType type, object value)
            {
                MySqlParameter parm = new MySqlParameter(name, type);
                parm.Value = value;
                return parm;
            }
            #endregion
    
            #region 存储过程的调用
            /// 
            /// 无参存储过程,用于插入修改删除表数据,无返回值
            /// 
            /// 存储过程脚本
            public 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 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 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 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
    
            #region 预留代码暂时用不上
            /*
            /// 
            /// 执行多条SQL语句,实现数据库事务。
            /// 
            /// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])
            public  void ExecuteSqlTran(Hashtable SQLStringList)
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    using (MySqlTransaction trans = conn.BeginTransaction())
                    {
                        MySqlCommand cmd = new MySqlCommand();
                        try
                        {
                            //循环
                            foreach (DictionaryEntry myDE in SQLStringList)
                            {
                                string cmdText = myDE.Key.ToString();
                                MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
                                PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                                int val = cmd.ExecuteNonQuery();
                                cmd.Parameters.Clear();
                            }
                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
            }
    
            /// 
            /// 执行多条语句,实现数据库事务
            /// 
            /// SQL语句的泛式表(key为sql语句,value是该语句的MySqlParameter[])
            /// 返回影响行数
            public  int ExecuteSqlTran(List cmdList)
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    using (MySqlTransaction trans = conn.BeginTransaction())
                    {
                        MySqlCommand cmd = new MySqlCommand();
                        try
                        {
                            int count = 0;
                            //循环
                            foreach (CommandInfo myDE in cmdList)
                            {
                                string cmdText = myDE.CommandText;
                                MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                                PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
    
                                if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                                {
                                    if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                                    {
                                        trans.Rollback();
                                        return 0;
                                    }
    
                                    object obj = cmd.ExecuteScalar();
                                    bool isHave = false;
                                    if (obj == null && obj == DBNull.Value)
                                    {
                                        isHave = false;
                                    }
                                    isHave = Convert.ToInt32(obj) > 0;
    
                                    if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                                    {
                                        trans.Rollback();
                                        return 0;
                                    }
                                    if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                                    {
                                        trans.Rollback();
                                        return 0;
                                    }
                                    continue;
                                }
                                int val = cmd.ExecuteNonQuery();
                                count += val;
                                if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                                {
                                    trans.Rollback();
                                    return 0;
                                }
                                cmd.Parameters.Clear();
                            }
                            trans.Commit();
                            return count;
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
            }
    
            /// 
            /// 执行多条SQL语句,实现数据库事务。
            /// 
            /// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])
            public  void ExecuteSqlTranWithIndentity(System.Collections.Generic.List SQLStringList)
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    using (MySqlTransaction trans = conn.BeginTransaction())
                    {
                        MySqlCommand cmd = new MySqlCommand();
                        try
                        {
                            int indentity = 0;
                            //循环
                            foreach (CommandInfo myDE in SQLStringList)
                            {
                                string cmdText = myDE.CommandText;
                                MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                                foreach (MySqlParameter q in cmdParms)
                                {
                                    if (q.Direction == ParameterDirection.InputOutput)
                                    {
                                        q.Value = indentity;
                                    }
                                }
                                PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                                int val = cmd.ExecuteNonQuery();
                                foreach (MySqlParameter q in cmdParms)
                                {
                                    if (q.Direction == ParameterDirection.Output)
                                    {
                                        indentity = Convert.ToInt32(q.Value);
                                    }
                                }
                                cmd.Parameters.Clear();
                            }
                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
            }
    
            /// 
            /// 执行多条SQL语句,实现数据库事务。
            /// 
            /// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])
            public  void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    using (MySqlTransaction trans = conn.BeginTransaction())
                    {
                        MySqlCommand cmd = new MySqlCommand();
                        try
                        {
                            int indentity = 0;
                            //循环
                            foreach (DictionaryEntry myDE in SQLStringList)
                            {
                                string cmdText = myDE.Key.ToString();
                                MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
                                foreach (MySqlParameter q in cmdParms)
                                {
                                    if (q.Direction == ParameterDirection.InputOutput)
                                    {
                                        q.Value = indentity;
                                    }
                                }
                                PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                                int val = cmd.ExecuteNonQuery();
                                foreach (MySqlParameter q in cmdParms)
                                {
                                    if (q.Direction == ParameterDirection.Output)
                                    {
                                        indentity = Convert.ToInt32(q.Value);
                                    }
                                }
                                cmd.Parameters.Clear();
                            }
                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
            }
    
            /// 
            /// 执行一条计算查询结果语句,返回查询结果(object)。
            /// 
            /// 计算查询结果语句
            /// 准备好的参数列表
            /// 查询结果(object)
            public  object GetSingle(string SQLString, params MySqlParameter[] cmdParms)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        try
                        {
                            PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                            object obj = cmd.ExecuteScalar();
                            cmd.Parameters.Clear();
                            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                            {
                                return null;
                            }
                            else
                            {
                                return obj;
                            }
                        }
                        catch (MySqlException e)
                        {
                            throw e;
                        }
                    }
                }
            }
    
    
           */
    
            #endregion
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
    • 448
    • 449
    • 450
    • 451
    • 452
    • 453
    • 454
    • 455
    • 456
    • 457
    • 458
    • 459
    • 460
    • 461
    • 462
    • 463
    • 464
    • 465
    • 466
    • 467
    • 468
    • 469
    • 470
    • 471
    • 472
    • 473
    • 474
    • 475
    • 476
    • 477
    • 478
    • 479
    • 480
    • 481
    • 482
    • 483
    • 484
    • 485
    • 486
    • 487
    • 488
    • 489
    • 490
    • 491
    • 492
    • 493
    • 494
    • 495
    • 496
    • 497
    • 498
    • 499
    • 500
    • 501
    • 502
    • 503
    • 504
    • 505
    • 506
    • 507
    • 508
    • 509
    • 510
    • 511
    • 512
    • 513
    • 514
    • 515
    • 516
    • 517
    • 518
    • 519
    • 520
    • 521
    • 522
    • 523
    • 524
    • 525
    • 526
    • 527
    • 528
    • 529
    • 530
    • 531
    • 532
    • 533
    • 534
    • 535
    • 536
    • 537
    • 538
    • 539
    • 540
    • 541
    • 542
    • 543
    • 544
    • 545
    • 546
    • 547
    • 548
    • 549
    • 550
    • 551
    • 552
    • 553
    • 554
    • 555
    • 556
    • 557
    • 558
    • 559
    • 560
    • 561
    • 562
    • 563
    • 564
    • 565
    • 566
    • 567
    • 568
    • 569
    • 570
    • 571
    • 572
    • 573
    • 574
    • 575
    • 576
    • 577
    • 578
    • 579
    • 580
    • 581
    • 582
    • 583
    • 584
    • 585
    • 586
    • 587
    • 588
    • 589
    • 590
    • 591
    • 592
    • 593
    • 594
    • 595
    • 596
    • 597
    • 598
    • 599
    • 600
    • 601
    • 602
    • 603
    • 604
    • 605
    • 606
    • 607
    • 608
    • 609
    • 610
    • 611
    • 612
    • 613
    • 614
    • 615
    • 616
    • 617
    • 618
    • 619
    • 620
    • 621
    • 622
    • 623
    • 624
    • 625
    • 626
    • 627
    • 628
    • 629
    • 630
    • 631
    • 632
    • 633
    • 634
    • 635
    • 636
    • 637
    • 638
    • 639
    • 640
    • 641
    • 642
    • 643
    • 644
    • 645
    • 646
    • 647
    • 648
    • 649
    • 650
    • 651
    • 652
    • 653
    • 654
    • 655
    • 656
    • 657
    • 658
    • 659
    • 660
    • 661
    • 662
    • 663
    • 664
    • 665
    • 666
    • 667
    • 668
    • 669
    • 670
    • 671
    • 672
    • 673
    • 674
    • 675
    • 676
    • 677
    • 678
    • 679
    • 680
    • 681
    • 682
    • 683
    • 684
    • 685
    • 686
    • 687
    • 688
    • 689
    • 690
    • 691
    • 692
    • 693
    • 694
    • 695
    • 696
    • 697
    • 698
    • 699
    • 700
    • 701
    • 702
    • 703
    • 704
    • 705
    • 706
    • 707
    • 708
    • 709
    • 710
    • 711
    • 712
    • 713
    • 714
    • 715
    • 716
    • 717
    • 718
    • 719
    • 720
    • 721
    • 722
    • 723
    • 724
    • 725
    • 726
    • 727
    • 728
    • 729
    • 730
    • 731
    • 732
    • 733
    • 734
    • 735
    • 736
    • 737
    • 738
    • 739
    • 740
    • 741
    • 742
    • 743
    • 744
    • 745
    • 746
    • 747
    • 748
    • 749
    • 750
    • 751
    • 752
    • 753
    • 754
    • 755
    • 756
    • 757
    • 758
    • 759
    • 760
    • 761
    • 762
    • 763
    • 764
    • 765
    • 766
    • 767
    • 768
    • 769
    • 770
    • 771
    • 772
    • 773
    • 774
    • 775
    • 776
    • 777
    • 778
    • 779
    • 780
    • 781
    • 782
    • 783
    • 784
    • 785
    • 786
    • 787
    • 788
    • 789
    • 790
    • 791
    • 792
    • 793
    • 794
    • 795
    • 796
    • 797
    • 798
    • 799
    • 800
    • 801
    • 802
    • 803
    • 804
    • 805
    • 806
    • 807
    • 808
    • 809
    • 810
    • 811
    • 812
    • 813
    • 814
    • 815
    • 816
    • 817
    • 818
    • 819
    • 820
    • 821
    • 822
    • 823
    • 824
    • 825
    • 826
    • 827
    • 828
    • 829
    • 830
    • 831
    • 832
    • 833
    • 834
    • 835
    • 836
    • 837
    • 838
    • 839
    • 840
    • 841
    • 842
    • 843
    • 844
    • 845
    • 846
    • 847
    • 848
    • 849
    • 850
    • 851
    • 852
    • 853
    • 854
    • 855
    • 856
    • 857
    • 858
    • 859
    • 860
    • 861
    • 862
    • 863
    • 864
    • 865
    • 866
    • 867
    • 868
    • 869
    • 870
    • 871
    • 872
    • 873
    • 874
    • 875
    • 876
    • 877
    • 878
    • 879
    • 880
    • 881
    • 882
    • 883
    • 884
    • 885
    • 886
    • 887
    • 888
    • 889
    • 890
    • 891
    • 892
    • 893
    • 894
    • 895
    • 896
    • 897
    • 898
    • 899
    • 900
    • 901
    • 902
    • 903
    • 904
    • 905
    • 906
    • 907
    • 908
    • 909
    • 910
    • 911
    • 912
    • 913
    • 914
    • 915
    • 916
    • 917
    • 918
    • 919
    • 920
    • 921
    • 922
    • 923
    • 924
    • 925
    • 926
    • 927
    • 928
    • 929
    • 930
    • 931
    • 932
    • 933
    • 934
    • 935
    • 936
    • 937
    • 938
    • 939
    • 940
    • 941
    • 942
    • 943
    • 944
    • 945
    • 946
    • 947
    • 948
    • 949
    • 950
    • 951
    • 952
    • 953
    • 954
    • 955
    • 956
    • 957
    • 958
    • 959
    • 960
    • 961
    • 962
    • 963
    • 964
    • 965
    • 966
    • 967
    • 968
    • 969
    • 970
    • 971
    • 972
    • 973
    • 974
    • 975
    • 976
    • 977
    • 978
    • 979
    • 980
    • 981
    • 982
    • 983
    • 984
    • 985
    • 986
    • 987
    • 988
    • 989
    • 990
    • 991
    • 992
    • 993
    • 994
    • 995
    • 996
    • 997
    • 998
    • 999
    • 1000
    • 1001

    2.2 特殊说明

    本底层库引用到组件 MySQL.Data.dll,比较恶心的是MySQL数据库迭代的比较猛,版本之间存在较大差异,有时候你会发现底层库连接不上,那是数据库连接串的问题。

    注意一定要使用,对应MySQL版本的MySQL.Data.dll,或者使用更高版本的MySQL.Data.dll,一般新版本兼容老版本。

    ①如何找到MySQL数据库对应的MySQL.Data.dll呢?
    我不建议你去网上下载,因为你计算机里就有。找到你的MySQL安装目录,你在里面搜一搜就可以找到它,我的版本是MySQL.Data 8.0.30.0
    在这里插入图片描述
    ②MySQL数据库支持的字符集如何查看?
    MySQL客户端client输入的字符,都是采用GBK编码的。mysql服务器存储的字符又是UTF8编码的。可以用一下语句查看数据库支持编码集:

    SHOW CHARACTER SET;查看数据库支持的所有的字符集。
    STATUS;查看系统当前状态,里面可以看到部分字符集设置。
    SHOW VARIABLES LIKE '%char%';查看系统字符集设置,包括所有的字符集设置
    
    SET character_set_client=gbk;设置客户端的字符集
    SET character_set_connection=utf8;设置连接器的字符集
    SET character_set_results=gbk;设置返回结果的字符集
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述
    ③不同版本的MySQL数据库,连接串的差异主要体现在什么地方?
    主要就是 用户名、字符集的差异,现在高版本的MySQL已经支持全中文建表,存储数据,你想要存取中文不乱码,可以在连接串中加入字符集。低版本的MySQL不支持这一点,因为某些字符集它还没有。
    我也不是每个版本都用过的,如果你调用底层库报错的话,一般就是“连接串”的问题,请重点关注。
    在这里插入图片描述

                //MySQL.Data 8.0.28.0
                //this.connectionString = $"server={server};port={port};user id={uid};password={pwd};database={BaseName};pooling=true;ConnectionTimeout=1800;CharSet=utf8";
                //MySQL.Data 8.0.26.0
                //this.connectionString = $"server={server};port={port};uid={uid};pwd={pwd};database={BaseName};SslMode=None;Charset=utf8";
                //MySQL.Data 8.0.30.0
                this.connectionString = $"server={server};port={port};uid={uid};pwd={pwd};database={BaseName};SslMode=None;pooling=false;Charset=utf8";
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    三、调用方法

    如何使用本底层库,先实例化类,默认从配置文件读取"数据库连接地址",然后就一条语句sqlHelper.ExecuteSql(l_strSql);执行完事。
    关于配置文件的读取方法,请看本专栏的文章《C#底层库–XML配置文件读写类(推荐阅读)》

                    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 sqlHelper = new MySQLHelper();
                    sqlHelper.ExecuteSql(l_strSql);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    程序运行效果:
    在这里插入图片描述

    四、项目样例

  • 相关阅读:
    用CMake编译项目 & CMake和g++的区别
    在Docker中使用MindSpore GPU版本
    thinkphp在apache、nginx和iis下的URL重写
    [附源码]Python计算机毕业设计Django汽车租赁管理系统
    在Docker里安装FastDFS分布式文件系统详细步骤
    程序员必知必会网络传输之TCP/IP协议族,共864页的详解文档让你原地起飞!
    【Python百日进阶-Web开发-Feffery】Day399 - fac实例:上海疫情地图
    java毕业设计大学生赞助系统mybatis+源码+调试部署+系统+数据库+lw
    241.为运算表达式设计优先级
    Jenkins详细配置
  • 原文地址:https://blog.csdn.net/youcheng_ge/article/details/126886379