C# 利用 ADO.NET 操作 MySQL 数据库

首先给大家看一下这个小项目的结构(一个 WebAPI 的小项目):

C# 利用 ADO.NET 操作 MySQL 数据库_第1张图片

上面红框里的文件是这篇文章所涉及的主要文件。

首先在你的项目中添加 MySQL 的支持,在 NuGet 上搜索 MySql 并安装第三方库(不要选错了哟~),如下图:

C# 利用 ADO.NET 操作 MySQL 数据库_第2张图片

创建一个MySQL数据库连接信息实体类,这个类会替代我们常用的连接字符串,而且可以实现对各个参数的配置、热修改。

///  MySQL数据库连接信息实体类
    /// 
    public class MySqlDBConnectInfo
    {
        ///  唯一别名(用来区分是哪个链接,推荐策略:服务地址-数据库名)
        /// 
        public string UniqueAlias { get; set; }

        ///  数据库服务连接地址,例:"127.0.0.1"
        /// 
        public string Server { get; set; }

        ///  数据库服务连接端口号
        /// 
        public uint Port { get; set; }

        ///  连接的数据库
        /// 
        public string Database { get; set; }

        ///  连接数据库的用户名
        /// 
        public string UserID { get; set; }

        ///  用户密码
        /// 
        public string Password { get; set; }

        ///  设置字符编码,例:"utf8"
        /// 
        public string CharacterSet { get; set; }

        ///  连接超时时间,单位秒
        /// 
        public uint ConnectionTimeout { get; set; }

        ///  数据库执行超时时间,单位秒
        /// 
        public uint DefaultCommandTimeout { get; set; }

        ///  是否开启连接池,true
        /// 
        public bool Pooling { get; set; }

        ///  连接池中最小连接数
        /// 
        public uint MinimumPoolSize { get; set; }

        ///  连接池中最大连接数
        /// 
        public uint MaximumPoolSize { get; set; }

        ///  连接池中连接对象存活时间,单位秒
        /// 
        public uint ConnectionLifeTime { get; set; }

        ///  连接是否使用压缩,true
        /// 
        public bool UseCompression { get; set; }

        ///  表示连接池程序是否会自动登记创建线程的当前事务语境中的连接,ture
        /// 
        public bool AutoEnlist { get; set; }

    }

 新建一个类 StartupInitMySqlConfig,用来控制程序启动时初始化MySQL数据库配置信息

///  启动时初始化MySQL数据库配置信息
    /// 
    public static class StartupInitMySqlConfig
    {

        ///  数据库连接信息配置文件 的 文件名 (MySqlConnectionConfig.xml)
        /// 
        private const string MySqlDBConnectConfigFilename = "MySqlConnectionConfig.xml";


        ///  唯一别名 的 存储值
        /// 
        private static string UniqueAliasSV = string.Empty;

        /// 
        /// 唯一别名 锁;避免同时被修改
        /// 
        private static readonly object _uniqueAliasLock = new object();


        ///  唯一别名(用来区分是哪个链接,推荐策略:服务地址_数据库名)
        /// 
        private static string uniqueAlias = string.Empty;

        ///  唯一别名(用来区分是哪个链接,推荐策略:服务地址_数据库名)
        /// 
        public static string UniqueAlias
        {
            get { return uniqueAlias; }
            set
            {
                uniqueAlias = value == null ? string.Empty : value;
            }
        }


        ///  声明一个[MySqlDBConnectInfo]数据库连接信息对象
        /// 
        private static MySqlDBConnectInfo dbConnectInfo;

        ///  获取[MySqlDBConnectInfo]数据库连接信息对象(默认取配置文件中的第一个连接对象)
        /// 
        public static MySqlDBConnectInfo DbConnectInfo
        {
            get
            {
                try
                {
                    lock (_uniqueAliasLock)
                    {
                        try
                        {
                            if (dbConnectInfo == null || UniqueAlias != UniqueAliasSV)
                            {
                                UniqueAliasSV = UniqueAlias;
                                string path = AppDomain.CurrentDomain.BaseDirectory + MySqlDBConnectConfigFilename;
                                if (!File.Exists(path))
                                {
                                    dbConnectInfo = null;
                                    throw new Exception("系统找不到数据库连接信息配置文件。");
                                }
                                else
                                {
                                    List dbConnectInfoList = XmlTool.XmlFlieToTObject>(path, Encoding.UTF8);
                                    if (string.IsNullOrWhiteSpace(UniqueAliasSV))
                                    {
                                        dbConnectInfo = dbConnectInfoList[0];
                                    }
                                    else
                                    {
                                        foreach (MySqlDBConnectInfo item in dbConnectInfoList)
                                        {
                                            if (item.UniqueAlias == UniqueAliasSV)
                                            {
                                                dbConnectInfo = item;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            dbConnectInfo = null;
                            throw new Exception("数据库连接信息配置文件[MySqlConfig.xml]转数据库连接信息对象[MySqlDBConnectInfo]时失败。\r\n" + ex.ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    dbConnectInfo = null;
                    throw new Exception("数据库连接信息配置文件[MySqlConfig.xml]转数据库连接信息对象[MySqlDBConnectInfo]时失败。\r\n" + ex.ToString());
                }
                return dbConnectInfo;
            }
            set { dbConnectInfo = value; }
        }


    }

下面是一个 MySQL数据库操作工具类【核心功能都在这】

///  MySQL数据库操作工具类
    /// 
    public class MySqlTool
    {

        ///  声明一个[MySqlDBConnectInfo]数据库连接信息对象
        /// 
        private MySqlDBConnectInfo mysqlDbConnectInfo;

        ///  无参构造函数(获取 MySqlConfig.xml 配置文件中的第一个连接对象)
        /// 
        public MySqlTool()
        {
            StartupInitMySqlConfig.UniqueAlias = string.Empty;
            mysqlDbConnectInfo = StartupInitMySqlConfig.DbConnectInfo;
        }

        ///  有参构造函数(获取 MySqlConfig.xml 配置文件中 UniqueAlias 参数所匹配的唯一别名的连接对象)
        /// 
        /// 连接对象的唯一别名,用来区分是哪个链接对象
        public MySqlTool(string uniqueAlias)
        {
            StartupInitMySqlConfig.UniqueAlias = uniqueAlias;
            mysqlDbConnectInfo = StartupInitMySqlConfig.DbConnectInfo;
        }


        ///  声明一个[MySqlConnection]连接对象
        /// 
        private MySqlConnection mysqlConnection;

        ///  获取[MySqlConnection]连接对象
        /// 
        private MySqlConnection MysqlConnection
        {
            get
            {
                if (mysqlDbConnectInfo == null)
                {
                    mysqlDbConnectInfo = StartupInitMySqlConfig.DbConnectInfo;
                }
                if (mysqlConnection == null)
                {
                    try
                    {
                        MySqlConnectionStringBuilder connectStr = new MySqlConnectionStringBuilder();

                        connectStr.Server = mysqlDbConnectInfo.Server;
                        connectStr.Port = mysqlDbConnectInfo.Port;
                        connectStr.Database = mysqlDbConnectInfo.Database;
                        connectStr.UserID = mysqlDbConnectInfo.UserID;
                        connectStr.Password = mysqlDbConnectInfo.Password;
                        connectStr.CharacterSet = mysqlDbConnectInfo.CharacterSet;
                        connectStr.ConnectionTimeout = mysqlDbConnectInfo.ConnectionTimeout;
                        connectStr.DefaultCommandTimeout = mysqlDbConnectInfo.DefaultCommandTimeout;
                        connectStr.Pooling = mysqlDbConnectInfo.Pooling;
                        connectStr.MinimumPoolSize = mysqlDbConnectInfo.MinimumPoolSize;
                        connectStr.MaximumPoolSize = mysqlDbConnectInfo.MaximumPoolSize;
                        connectStr.ConnectionLifeTime = mysqlDbConnectInfo.ConnectionLifeTime;
                        connectStr.UseCompression = mysqlDbConnectInfo.UseCompression;
                        connectStr.AutoEnlist = mysqlDbConnectInfo.AutoEnlist;

                        mysqlConnection = new MySqlConnection(connectStr.GetConnectionString(true));
                    }
                    catch (Exception ex)
                    {
                        mysqlConnection = null;
                        throw new Exception("创建数据库连接时发生异常。\r\n" + ex.ToString());
                    }
                }
                return mysqlConnection;
            }
        }

        ///  获取当前对象已存在的连接信息[MySqlDBConnectInfo]
        /// 
        /// 
        public MySqlDBConnectInfo GetMySqlConnectInfo()
        {
            return mysqlDbConnectInfo;
        }


        ///  打开数据库连接
        /// 
        public void OpenConnect()
        {
            if (MysqlConnection.State == ConnectionState.Closed)
            {
                try
                {
                    MysqlConnection.Open();
                }
                catch (Exception ex)
                {
                    StartupInitMySqlConfig.DbConnectInfo = null;
                    throw new Exception("打开数据库连接时发生异常。\r\n" + ex.ToString());
                }
            }
            else if (MysqlConnection.State == ConnectionState.Broken)
            {
                try
                {
                    MysqlConnection.Close();
                    MysqlConnection.Open();
                }
                catch (Exception ex)
                {
                    StartupInitMySqlConfig.DbConnectInfo = null;
                    throw new Exception("打开数据库连接时发生异常。\r\n" + ex.ToString());
                }
            }
        }

        ///  关闭数据库连接
        /// 
        public void CloseConnect()
        {
            if (MysqlConnection.State != ConnectionState.Closed)
            {
                try
                {
                    MysqlConnection.Close();
                }
                catch (Exception ex)
                {
                    throw new Exception("关闭数据库连接时发生异常。\r\n" + ex.ToString());
                }
            }
        }


        ///  声明一个[MySqlTransaction]事务处理对象
        /// 
        private MySqlTransaction mysqlTransaction;

        ///  开启事务处理
        /// 
        public void BeginTransaction()
        {
            try
            {
                mysqlTransaction = MysqlConnection.BeginTransaction();
            }
            catch (Exception ex)
            {
                throw new Exception("开始事务处理时发生异常。\r\n" + ex.ToString());
            }
        }

        ///  提交事务
        /// 
        public void Commit()
        {
            try
            {
                if (mysqlTransaction != null)
                {
                    mysqlTransaction.Commit();
                    mysqlTransaction.Dispose();
                    mysqlTransaction = null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("提交事务时发生异常。\r\n" + ex.ToString());
            }
        }

        ///  回滚事务
        /// 
        public void Rollback()
        {
            try
            {
                if (mysqlTransaction != null)
                {
                    mysqlTransaction.Rollback();
                    mysqlTransaction.Dispose();
                    mysqlTransaction = null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("回滚事务时发生异常。\r\n" + ex.ToString());
            }
        }


        ///  执行SQL语句,返回受影响行数
        /// 
        /// string:SQL语句
        /// Dictionary:SQL参数化
        /// int
        public int ExecuteNonQuery(string sql, Dictionary dicParam = null)
        {
            int row = -1;
            try
            {
                using (MySqlCommand command = MysqlConnection.CreateCommand())
                {
                    try
                    {
                        command.CommandText = sql;
                        if (dicParam != null && dicParam.Count > 0)
                        {
                            foreach (KeyValuePair kvp in dicParam)
                            {
                                command.Parameters.AddWithValue(kvp.Key, kvp.Value);
                            }
                        }
                        row = command.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        row = -1;
                        throw new Exception("执行SQL语句时发生异常[ExecuteNonQuery()]。\r\n" + ex.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                row = -1;
                throw new Exception("执行SQL语句时发生异常[ExecuteNonQuery()]。\r\n" + ex.ToString());
            }
            return row;
        }

        ///  执行SQL查询,返回第一行第一列的值(object对象)。【例如:count()函数】
        /// 
        /// string:SQL语句
        /// Dictionary:SQL参数化
        /// object
        public object ExecuteScalar(string sql, Dictionary dicParam = null)
        {
            object obj = null;
            try
            {
                using (MySqlCommand command = MysqlConnection.CreateCommand())
                {
                    try
                    {
                        command.CommandText = sql;
                        if (dicParam != null && dicParam.Count > 0)
                        {
                            foreach (KeyValuePair kvp in dicParam)
                            {
                                command.Parameters.AddWithValue(kvp.Key, kvp.Value);
                            }
                        }
                        obj = command.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        obj = null;
                        throw new Exception("执行SQL语句查询时发生异常[ExecuteScalar()]。\r\n" + ex.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                obj = null;
                throw new Exception("执行SQL语句查询时发生异常[ExecuteScalar()]。\r\n" + ex.ToString());
            }
            return obj;
        }

        ///  执行SQL查询,返回一个[ MySqlDataReader ]只进只读对象
        /// 
        /// string:SQL语句
        /// Dictionary:SQL参数化
        /// (object)MySqlDataReader
        public object ExecuteReader(string sql, Dictionary dicParam = null)
        {
            MySqlDataReader reader = null;
            try
            {
                using (MySqlCommand command = MysqlConnection.CreateCommand())
                {
                    try
                    {
                        command.CommandText = sql;
                        if (dicParam != null && dicParam.Count > 0)
                        {
                            foreach (KeyValuePair kvp in dicParam)
                            {
                                command.Parameters.AddWithValue(kvp.Key, kvp.Value);
                            }
                        }
                        reader = command.ExecuteReader();
                    }
                    catch (Exception ex)
                    {
                        reader = null;
                        throw new Exception("执行SQL语句查询时发生异常[ExecuteReader()]。\r\n" + ex.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                reader = null;
                throw new Exception("执行SQL语句查询时发生异常[ExecuteReader()]。\r\n" + ex.ToString());
            }
            return reader;
        }

        ///  执行查询,返回一个DataTable对象
        /// 
        /// string:SQL语句
        /// Dictionary:SQL参数化
        /// DataTable
        public DataTable QueryData_DataTable(string sql, Dictionary dicParam = null)
        {
            DataTable dt = new DataTable();
            try
            {
                using (MySqlDataAdapter da = new MySqlDataAdapter())
                {
                    using (MySqlCommand command = MysqlConnection.CreateCommand())
                    {
                        try
                        {
                            command.CommandText = sql;
                            if (dicParam != null && dicParam.Count > 0)
                            {
                                foreach (KeyValuePair kvp in dicParam)
                                {
                                    command.Parameters.AddWithValue(kvp.Key, kvp.Value);
                                }
                            }
                            da.SelectCommand = command;
                            da.Fill(dt);
                        }
                        catch (Exception ex)
                        {
                            dt = null;
                            throw new Exception("执行SQL语句查询时发生异常[QueryData_DataTable()]。\r\n" + ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                dt = null;
                throw new Exception("执行SQL语句查询时发生异常[QueryData_DataTable()]。\r\n" + ex.ToString());
            }
            return dt;
        }

        ///  执行查询,返回一个DataSet对象
        /// 
        /// string:SQL语句
        /// Dictionary:SQL参数化
        /// string:映射表名称
        /// DataSet
        public DataSet QueryData_DataSet(string sql, Dictionary dicParam = null, string srcTable = null)
        {
            DataSet ds = new DataSet();
            try
            {
                using (MySqlDataAdapter da = new MySqlDataAdapter())
                {
                    using (MySqlCommand command = MysqlConnection.CreateCommand())
                    {
                        try
                        {
                            command.CommandText = sql;
                            if (dicParam != null && dicParam.Count > 0)
                            {
                                foreach (KeyValuePair kvp in dicParam)
                                {
                                    command.Parameters.AddWithValue(kvp.Key, kvp.Value);
                                }
                            }
                            da.SelectCommand = command;
                            if (string.IsNullOrWhiteSpace(srcTable))
                            {
                                da.Fill(ds);
                            }
                            else
                            {
                                da.Fill(ds, srcTable);
                            }
                        }
                        catch (Exception ex)
                        {
                            ds = null;
                            throw new Exception("执行SQL语句查询时发生异常[QueryData_DataSet()]。\r\n" + ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ds = null;
                throw new Exception("执行SQL语句查询时发生异常[QueryData_DataSet()]。\r\n" + ex.ToString());
            }
            return ds;
        }


        ///  新增数据通用方法(字段名数组与字段值数组必须一一对应)
        /// 
        /// 数据库表名称
        /// 数据库字段名数组
        /// 数据库字段值数组
        /// 
        public int InsertSqlExe(string tableName, string[] fieldArray, object[] valueArray)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((fieldArray == null) || (valueArray == null) || (fieldArray.Length < 1) || (valueArray.Length < 1) || (fieldArray.Length != valueArray.Length))
            {
                throw new Exception("字段/值 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            try
            {
                #region 动态产生SQL语句

                sqlStr.AppendLine("INSERT INTO " + tableName);
                sqlStr.AppendLine("(");
                for (int f = 0; f < fieldArray.Length; f++)
                {
                    if (f == fieldArray.Length - 1)
                    {
                        sqlStr.AppendLine(fieldArray[f]);
                    }
                    else
                    {
                        sqlStr.AppendLine(fieldArray[f] + ",");
                    }
                }
                sqlStr.AppendLine(")");
                sqlStr.AppendLine("VALUES");
                sqlStr.AppendLine("(");
                for (int f = 0; f < fieldArray.Length; f++)
                {
                    if (f == fieldArray.Length - 1)
                    {
                        sqlStr.AppendLine("?" + fieldArray[f]);
                    }
                    else
                    {
                        sqlStr.AppendLine("?" + fieldArray[f] + ",");
                    }
                }
                sqlStr.AppendLine(")");

                #endregion

                #region 动态参数赋值

                for (int v = 0; v < valueArray.Length; v++)
                {
                    dicParam.Add("?" + fieldArray[v], valueArray[v]);
                }

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行新增通用方法时发生异常[InsertSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }

        ///  新增数据通用方法(字段名集合与字段值集合必须一一对应)
        /// 
        /// 数据库表名称
        /// 数据库字段名集合
        /// 数据库字段值集合
        /// 
        public int InsertSqlExe(string tableName, List fieldList, List valueList)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((fieldList == null) || (valueList == null) || (fieldList.Count < 1) || (valueList.Count < 1) || (fieldList.Count != valueList.Count))
            {
                throw new Exception("字段/值 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            try
            {
                #region 动态产生SQL语句

                sqlStr.AppendLine("INSERT INTO " + tableName);
                sqlStr.AppendLine("(");
                for (int f = 0; f < fieldList.Count; f++)
                {
                    if (f == fieldList.Count - 1)
                    {
                        sqlStr.AppendLine(fieldList[f]);
                    }
                    else
                    {
                        sqlStr.AppendLine(fieldList[f] + ",");
                    }
                }
                sqlStr.AppendLine(")");
                sqlStr.AppendLine("VALUES");
                sqlStr.AppendLine("(");
                for (int f = 0; f < fieldList.Count; f++)
                {
                    if (f == fieldList.Count - 1)
                    {
                        sqlStr.AppendLine("?" + fieldList[f]);
                    }
                    else
                    {
                        sqlStr.AppendLine("?" + fieldList[f] + ",");
                    }
                }
                sqlStr.AppendLine(")");

                #endregion

                #region 动态参数赋值

                for (int v = 0; v < valueList.Count; v++)
                {
                    dicParam.Add("?" + fieldList[v], valueList[v]);
                }

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行新增通用方法时发生异常[InsertSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }


        ///  修改数据通用方法(修改字段名数组与修改字段值数组必须一一对应;须显式指定主键列/唯一列)
        /// 
        /// 数据库表名称
        /// 主键列/唯一列字段名
        /// 主键列/唯一列字段值
        /// 修改字段名数组
        /// 修改字段值数组
        /// 空值是否参与数据修改,默认true,false忽略空值进行数据修改
        /// 
        public int UpdateSqlExe(string tableName, string pkField, object pkValue, string[] fieldArray, object[] valueArray, bool nullIsJoin = true)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((string.IsNullOrWhiteSpace(pkField)) || pkValue == null)
            {
                throw new Exception("主键列/唯一列 参数错误。");
            }

            if ((fieldArray == null) || (valueArray == null) || (fieldArray.Length < 1) || (valueArray.Length < 1) || (fieldArray.Length != valueArray.Length))
            {
                throw new Exception("字段/值 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            List fieldList = null;
            List valueList = null;

            try
            {
                #region 忽略空参数处理

                if (!nullIsJoin)
                {
                    fieldList = new List();
                    valueList = new List();

                    List fieldListNew = new List(fieldArray);
                    List valueListNew = new List(valueArray);

                    for (int i = 0; i < valueListNew.Count; i++)
                    {
                        if ((valueListNew[i] != null) && (!string.IsNullOrWhiteSpace(Convert.ToString(valueListNew[i]))))
                        {
                            fieldList.Add(fieldListNew[i]);
                            valueList.Add(valueListNew[i]);
                        }
                    }

                    if ((fieldList == null) || (valueList == null) || (fieldList.Count < 1) || (valueList.Count < 1) || (fieldList.Count != valueList.Count))
                    {
                        throw new Exception("字段/值 参数错误。");
                    }
                }
                else
                {
                    fieldList = new List(fieldArray);
                    valueList = new List(valueArray);
                }

                #endregion

                #region 动态产生SQL语句

                sqlStr.AppendLine("UPDATE " + tableName);
                sqlStr.AppendLine("SET");
                for (int f = 0; f < fieldList.Count; f++)
                {
                    if (f == fieldList.Count - 1)
                    {
                        sqlStr.AppendLine(fieldList[f] + " = ?" + fieldList[f]);
                    }
                    else
                    {
                        sqlStr.AppendLine(fieldList[f] + " = ?" + fieldList[f] + ",");
                    }
                }
                sqlStr.AppendLine("WHERE 1 = 1");
                sqlStr.AppendLine("AND " + pkField + " = ?" + pkField);

                #endregion

                #region 动态参数赋值

                for (int v = 0; v < valueArray.Length; v++)
                {
                    dicParam.Add("?" + fieldArray[v], valueArray[v]);
                }
                dicParam.Add("?" + pkField, pkValue);

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行修改通用方法时发生异常[UpdateSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }

        ///  修改数据通用方法(修改字段名集合与修改字段值集合必须一一对应;须显式指定主键列/唯一列)
        /// 
        /// 数据库表名称
        /// 条件字段名集合
        /// 条件字段值集合
        /// 修改字段名集合
        /// 修改字段值集合
        /// 空值是否参与数据修改。默认 true,空值参与数据修改;false,忽略空值进行数据修改
        /// 
        public int UpdateSqlExe(string tableName, string pkField, object pkValue, List fieldList, List valueList, bool nullIsJoin = true)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((string.IsNullOrWhiteSpace(pkField)) || pkValue == null)
            {
                throw new Exception("主键列/唯一列 参数错误。");
            }

            if ((fieldList == null) || (valueList == null) || (fieldList.Count < 1) || (valueList.Count < 1) || (fieldList.Count != valueList.Count))
            {
                throw new Exception("字段/值 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            try
            {
                #region 忽略空参数处理

                if (!nullIsJoin)
                {
                    List fieldListNew = new List();
                    List valueListNew = new List();

                    fieldListNew = fieldList;
                    valueListNew = valueList;

                    fieldList.Clear();
                    valueList.Clear();

                    for (int i = 0; i < valueListNew.Count; i++)
                    {
                        if ((valueListNew[i] != null) && (!string.IsNullOrWhiteSpace(Convert.ToString(valueListNew[i]))))
                        {
                            fieldList.Add(fieldListNew[i]);
                            valueList.Add(valueListNew[i]);
                        }
                    }

                    if ((fieldList == null) || (valueList == null) || (fieldList.Count < 1) || (valueList.Count < 1) || (fieldList.Count != valueList.Count))
                    {
                        throw new Exception("字段/值 参数错误。");
                    }
                }

                #endregion

                #region 动态产生SQL语句

                sqlStr.AppendLine("UPDATE " + tableName);
                sqlStr.AppendLine("SET");
                for (int f = 0; f < fieldList.Count; f++)
                {
                    if (f == fieldList.Count - 1)
                    {
                        sqlStr.AppendLine(fieldList[f] + " = ?" + fieldList[f]);
                    }
                    else
                    {
                        sqlStr.AppendLine(fieldList[f] + " = ?" + fieldList[f] + ",");
                    }
                }
                sqlStr.AppendLine("WHERE 1 = 1");
                sqlStr.AppendLine("AND " + pkField + " = ?" + pkField);

                #endregion

                #region 动态参数赋值

                for (int v = 0; v < valueList.Count; v++)
                {
                    dicParam.Add("?" + fieldList[v], valueList[v]);
                }
                dicParam.Add("?" + pkField, pkValue);

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行修改通用方法时发生异常[UpdateSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }

        ///  修改数据通用方法(条件字段名数组与条件字段值数组必须一一对应;修改字段名数组与修改字段值数组必须一一对应)
        /// 注:条件字段与条件值目前只支持“=”等号运算符(其他暂不考虑,自行写SQL语句)
        /// 
        /// 数据库表名称
        /// 条件字段名数组
        /// 条件字段值数组
        /// 修改字段名数组
        /// 修改字段值数组
        /// 空值是否参与数据修改,默认true,false忽略空值进行数据修改
        /// 
        public int UpdateSqlExe(string tableName, string[] conditionField, object[] conditionValue, string[] fieldArray, object[] valueArray, bool nullIsJoin = true)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((conditionField == null) || (conditionValue == null) || (conditionField.Length < 1) || (conditionValue.Length < 1) || (conditionField.Length != conditionValue.Length))
            {
                throw new Exception("条件 的 字段/值 参数错误。");
            }

            if ((fieldArray == null) || (valueArray == null) || (fieldArray.Length < 1) || (valueArray.Length < 1) || (fieldArray.Length != valueArray.Length))
            {
                throw new Exception("字段/值 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            List fieldList = null;
            List valueList = null;

            try
            {
                #region 忽略空参数处理

                if (!nullIsJoin)
                {
                    fieldList = new List();
                    valueList = new List();

                    List fieldListNew = new List(fieldArray);
                    List valueListNew = new List(valueArray);

                    for (int i = 0; i < valueListNew.Count; i++)
                    {
                        if ((valueListNew[i] != null) && (!string.IsNullOrWhiteSpace(Convert.ToString(valueListNew[i]))))
                        {
                            fieldList.Add(fieldListNew[i]);
                            valueList.Add(valueListNew[i]);
                        }
                    }

                    if ((fieldList == null) || (valueList == null) || (fieldList.Count < 1) || (valueList.Count < 1) || (fieldList.Count != valueList.Count))
                    {
                        throw new Exception("字段/值 参数错误。");
                    }
                }
                else
                {
                    fieldList = new List(fieldArray);
                    valueList = new List(valueArray);
                }

                #endregion

                #region 动态产生SQL语句

                sqlStr.AppendLine("UPDATE " + tableName);
                sqlStr.AppendLine("SET");
                for (int f = 0; f < fieldList.Count; f++)
                {
                    if (f == fieldList.Count - 1)
                    {
                        sqlStr.AppendLine(fieldList[f] + " = ?" + fieldList[f]);
                    }
                    else
                    {
                        sqlStr.AppendLine(fieldList[f] + " = ?" + fieldList[f] + ",");
                    }
                }
                sqlStr.AppendLine("WHERE 1 = 1");
                for (int c = 0; c < conditionField.Length; c++)
                {
                    sqlStr.AppendLine("AND " + conditionField[c] + " = ?" + conditionField[c]);
                }

                #endregion

                #region 动态参数赋值

                for (int v = 0; v < valueList.Count; v++)
                {
                    dicParam.Add("?" + fieldList[v], valueList[v]);
                }
                for (int cv = 0; cv < conditionValue.Length; cv++)
                {
                    dicParam.Add("?" + conditionField[cv], conditionValue[cv]);
                }

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行修改通用方法时发生异常[UpdateSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }

        ///  修改数据通用方法(条件字段名集合与条件字段值集合必须一一对应,修改字段名集合与修改字段值集合必须一一对应)
        /// 注:条件字段与条件值目前只支持“=”等号运算符(其他暂不考虑,自行写SQL语句)
        /// 
        /// 数据库表名称
        /// 条件字段名集合
        /// 条件字段值集合
        /// 修改字段名集合
        /// 修改字段值集合
        /// 空值是否参与数据修改。默认 true,空值参与数据修改;false,忽略空值进行数据修改
        /// 
        public int UpdateSqlExe(string tableName, List conditionFieldList, List conditionValueList, List fieldList, List valueList, bool nullIsJoin = true)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((conditionFieldList == null) || (conditionValueList == null) || (conditionFieldList.Count < 1) || (conditionValueList.Count < 1) || (conditionFieldList.Count != conditionValueList.Count))
            {
                throw new Exception("条件 字段/值 参数错误。");
            }

            if ((fieldList == null) || (valueList == null) || (fieldList.Count < 1) || (valueList.Count < 1) || (fieldList.Count != valueList.Count))
            {
                throw new Exception("字段/值 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            try
            {
                #region 忽略空参数处理

                if (!nullIsJoin)
                {
                    List fieldListNew = new List();
                    List valueListNew = new List();

                    fieldListNew = fieldList;
                    valueListNew = valueList;

                    fieldList.Clear();
                    valueList.Clear();

                    for (int i = 0; i < valueListNew.Count; i++)
                    {
                        if ((valueListNew[i] != null) && (!string.IsNullOrWhiteSpace(Convert.ToString(valueListNew[i]))))
                        {
                            fieldList.Add(fieldListNew[i]);
                            valueList.Add(valueListNew[i]);
                        }
                    }

                    if ((fieldList == null) || (valueList == null) || (fieldList.Count < 1) || (valueList.Count < 1) || (fieldList.Count != valueList.Count))
                    {
                        throw new Exception("字段/值 参数错误。");
                    }
                }

                #endregion

                #region 动态产生SQL语句

                sqlStr.AppendLine("UPDATE " + tableName);
                sqlStr.AppendLine("SET");
                for (int f = 0; f < fieldList.Count; f++)
                {
                    if (f == fieldList.Count - 1)
                    {
                        sqlStr.AppendLine(fieldList[f] + " = ?" + fieldList[f]);
                    }
                    else
                    {
                        sqlStr.AppendLine(fieldList[f] + " = ?" + fieldList[f] + ",");
                    }
                }
                sqlStr.AppendLine("WHERE 1 = 1");
                for (int c = 0; c < conditionFieldList.Count; c++)
                {
                    sqlStr.AppendLine("AND " + conditionFieldList[c] + " = ?" + conditionFieldList[c]);
                }

                #endregion

                #region 动态参数赋值

                for (int v = 0; v < valueList.Count; v++)
                {
                    dicParam.Add("?" + fieldList[v], valueList[v]);
                }
                for (int cv = 0; cv < conditionValueList.Count; cv++)
                {
                    dicParam.Add("?" + conditionFieldList[cv], conditionValueList[cv]);
                }

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行修改通用方法时发生异常[UpdateSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }


        ///  删除数据通用方法(须显式指定主键列/唯一列)
        /// 
        /// 数据库表名称
        /// 主键列字段名
        /// 主键列字段值
        /// 
        public int DeleteSqlExe(string tableName, string pkField, object pkValue)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((string.IsNullOrWhiteSpace(pkField)) || pkValue == null)
            {
                throw new Exception("主键列 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            try
            {
                #region 动态产生SQL语句

                sqlStr.AppendLine("DELETE FROM " + tableName);
                sqlStr.AppendLine("WHERE " + pkField + " = ?" + pkField);

                #endregion

                #region 动态参数赋值

                dicParam.Add("?" + pkField, pkValue);

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行删除通用方法时发生异常[DeleteSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }

        ///  删除数据通用方法(条件字段名数组与条件字段值数组必须一一对应)
        /// 
        /// 数据库表名称
        /// 条件字段名数组
        /// 条件字段值数组
        /// 
        public int DeleteSqlExe(string tableName, string[] conditionField, object[] conditionValue)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((conditionField == null) || (conditionValue == null) || (conditionField.Length < 1) || (conditionValue.Length < 1) || (conditionField.Length != conditionValue.Length))
            {
                throw new Exception("条件 字段/值 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            try
            {
                #region 动态产生SQL语句

                sqlStr.AppendLine("DELETE FROM " + tableName);
                sqlStr.AppendLine("WHERE 1 = 1");
                for (int cf = 0; cf < conditionField.Length; cf++)
                {
                    sqlStr.AppendLine("AND " + conditionField[cf] + " = ?" + conditionField[cf]);
                }

                #endregion

                #region 动态参数赋值

                for (int vf = 0; vf < conditionValue.Length; vf++)
                {
                    dicParam.Add("?" + conditionValue[vf], conditionValue[vf]);
                }

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行删除通用方法时发生异常[DeleteSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }

        ///  删除数据通用方法(条件字段名集合与条件字段值集合必须一一对应)
        /// 
        /// 数据库表名称
        /// 条件字段名集合
        /// 条件字段值集合
        /// 
        public int DeleteSqlExe(string tableName, List conditionFieldList, List conditionValueList)
        {
            int row = -1;

            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new Exception("表名 参数错误。");
            }

            if ((conditionFieldList == null) || (conditionValueList == null) || (conditionFieldList.Count < 1) || (conditionValueList.Count < 1) || (conditionFieldList.Count != conditionValueList.Count))
            {
                throw new Exception("条件 字段/值 参数错误。");
            }

            StringBuilder sqlStr = new StringBuilder();
            Dictionary dicParam = new Dictionary();

            try
            {
                #region 动态产生SQL语句

                sqlStr.AppendLine("DELETE FROM " + tableName);
                sqlStr.AppendLine("WHERE 1 = 1");
                for (int cf = 0; cf < conditionFieldList.Count; cf++)
                {
                    sqlStr.AppendLine("AND " + conditionFieldList[cf] + " = ?" + conditionFieldList[cf]);
                }

                #endregion

                #region 动态参数赋值

                for (int vf = 0; vf < conditionValueList.Count; vf++)
                {
                    dicParam.Add("?" + conditionFieldList[vf], conditionValueList[vf]);
                }

                #endregion

                #region 执行SQL

                row = ExecuteNonQuery(sqlStr.ToString(), dicParam);

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("执行删除通用方法时发生异常[DeleteSqlExe()]。\r\n" + ex.ToString());
            }

            return row;
        }


    } 
  

 接下来我们配置启动时代码 Global.asax 

public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);


            //启动时读取数据库连接信息配置文件(MySqlConnectionConfig.xml)
            try
            {
                MySqlDBConnectInfo dbConnectInfo = StartupInitMySqlConfig.DbConnectInfo;
                if (dbConnectInfo == null)
                {
                    throw new Exception("系统获取不到数据库连接信息。");
                }
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog("【启动异常】从配置文件中获取 MySql 连接信息,发生异常", ex.ToString());
            }
        }
    }

MySqlConnectionConfig.xml 配置文件:



  
  
    
    185.**.36.12-DBName
    
    
    185.**.36.12
    
    3306
    
    DBName
    
    UserName
    
    UserPwd
    
    
    utf8
    
    60
    
    60
    
    true
    
    20
    
    50
    
    1200
    
    true
    
    true
  

上面代码中用到的 JsonTool XmlTool 都在我之前的博文中。

下面给一个 MySqlTool 的使用例子:

C# 利用 ADO.NET 操作 MySQL 数据库_第3张图片

希望给你带来参考和帮助。

你可能感兴趣的:(后台开发,C#,ADO.NET)