Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: MySqlHelper.cs代码如下: using System; using System.Collections.Generic; using System.Linq; using System.

MySqlHelper.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using System.Collections;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
using System.Configuration;
using System.IO;



public abstract class MySqlHelper
{
    //Get the database connectionstring, which are static variables and readonly, all project documents can be used directly, but can not modify it 
    //the database connectionString 
    //public static readonly string connectionStringManager = ConfigurationManager.ConnectionStrings["MYSQLConnectionString"].ConnectionString;
    public static string ConnectionStringManager
    {
        get { return connectionStringManager; }
    }



    //This connectionString for the local test
    public static readonly string connectionStringManager = System.Configuration.ConfigurationManager.AppSettings["MySQLConnString"];
    //ConfigurationManager.ConnectionStrings["MySQLConnString"].ConnectionString;

    //hashtable to store the parameter information, the hash table can store any type of argument 
    //Here the hashtable is static types of static variables, since it is static, that is a definition of global use.
    //All parameters are using this hash table, how to ensure that others in the change does not affect their time to read it
    //Before ,the method can use the lock method to lock the table, does not allow others to modify.when it has readed then  unlocked table.
    //Now .NET provides a HashTable's Synchronized methods to achieve the same function, no need to manually lock, completed directly by the system framework 
    private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

    /// <summary>
    /// Execute a SqlCommand command that does not return value, by appointed and specified connectionstring 
    /// The parameter list using parameters that in array forms
    /// </summary>
    /// <remarks>
    /// Usage example: 
    /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure,
    /// "PublishOrders", new MySqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connectionString">a valid database connectionstring</param>
    /// <param name="cmdType">MySqlCommand command type (stored procedures, T-SQL statement, and so on.) </param>
    /// <param name="cmdText">stored procedure name or T-SQL statement</param>
    /// <param name="commandParameters">MySqlCommand to provide an array of parameters used in the list</param>
    /// <returns>Returns a value that means number of rows affected/returns>
    public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
    {
        MySqlCommand cmd = new MySqlCommand();

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

    /// <summary>
    /// Execute a SqlCommand command that does not return value, by appointed and specified connectionstring 
    /// The parameter list using parameters that in array forms
    /// </summary>
    /// <remarks>
    /// Usage example: 
    /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure,
    /// "PublishOrders", new MySqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="cmdType">MySqlCommand command type (stored procedures, T-SQL statement, and so on.) </param>
    /// <param name="connectionString">a valid database connectionstring</param>
    /// <param name="cmdText">stored procedure name or T-SQL statement</param>
    /// <param name="commandParameters">MySqlCommand to provide an array of parameters used in the list</param>
    /// <returns>Returns true or false </returns>
    public static bool ExecuteNonQuery(CommandType cmdType, string connectionString, string cmdText, params MySqlParameter[] commandParameters)
    {
        MySqlCommand cmd = new MySqlCommand();

        using (MySqlConnection conn = new MySqlConnection(connectionString))
        {
            PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
            try
            {
                int val = cmd.ExecuteNonQuery();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                cmd.Parameters.Clear();
            }
        }
    }
    /// <summary>
    /// Execute a SqlCommand command that does not return value, by appointed and specified connectionstring 
    /// Array of form parameters using the parameter list 
    /// </summary>
    /// <param name="conn">connection</param>
    /// <param name="cmdType">MySqlCommand command type (stored procedures, T-SQL statement, and so on.)</param>
    /// <param name="cmdText">stored procedure name or T-SQL statement</param>
    /// <param name="commandParameters">MySqlCommand to provide an array of parameters used in the list</param>
    /// <returns>Returns a value that means number of rows affected</returns>
    public static int ExecuteNonQuery(MySqlConnection conn, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
    {
        MySqlCommand cmd = new MySqlCommand();
        PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
        int val = cmd.ExecuteNonQuery();
        cmd.Parameters.Clear();
        return val;
    }

    /// <summary>
    /// Execute a SqlCommand command that does not return value, by appointed and specified connectionstring 
    /// Array of form parameters using the parameter list 
    /// </summary>
    /// <param name="conn">sql Connection that has transaction</param>
    /// <param name="cmdType">SqlCommand command type (stored procedures, T-SQL statement, and so on.)</param>
    /// <param name="cmdText">stored procedure name or T-SQL statement</param>
    /// <param name="commandParameters">MySqlCommand to provide an array of parameters used in the list</param>
    /// <returns>Returns a value that means number of rows affected </returns>
    public static int ExecuteNonQuery(MySqlTransaction trans, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
    {
        MySqlCommand cmd = new MySqlCommand();
        PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
        int val = cmd.ExecuteNonQuery();
        cmd.Parameters.Clear();
        return val;
    }

    /// <summary>
    /// Call method of sqldatareader to read data
    /// </summary>
    /// <param name="connectionString">connectionstring</param>
    /// <param name="cmdType">command type, such as using stored procedures: CommandType.StoredProcedure</param>
    /// <param name="cmdText">stored procedure name or T-SQL statement</param>
    /// <param name="commandParameters">parameters</param>
    /// <returns>SqlDataReader type of data collection</returns>
    public static MySqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
    {
        MySqlCommand cmd = new MySqlCommand();
        MySqlConnection conn = new MySqlConnection(connectionString);

        // we use a try/catch here because if the method throws an exception we want to 
        // close the connection throw code, because no datareader will exist, hence the 
        // commandBehaviour.CloseConnection will not work
        try
        {
            PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
            MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            return rdr;
        }
        catch
        {
            conn.Close();
            throw;
        }
    }

    /// <summary>
    /// use the ExectueScalar to read a single result
    /// </summary>
    /// <param name="connectionString">connectionstring</param>
    /// <param name="cmdType">command type, such as using stored procedures: CommandType.StoredProcedure</param>
    /// <param name="cmdText">stored procedure name or T-SQL statement</param>
    /// <param name="commandParameters">parameters</param>
    /// <returns>a value in object type</returns>
    public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
    {
        MySqlCommand cmd = new MySqlCommand();

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

    public static DataSet GetDataSet(string connectionString, string cmdText, params MySqlParameter[] commandParameters)
    {
        DataSet retSet = new DataSet();
        using (MySqlDataAdapter msda = new MySqlDataAdapter(cmdText, connectionString))
        {
            msda.Fill(retSet);
        }
        return retSet;
    }

    /// <summary>
    /// cache the parameters in the HashTable
    /// </summary>
    /// <param name="cacheKey">hashtable key name</param>
    /// <param name="commandParameters">the parameters that need to cached</param>
    public static void CacheParameters(string cacheKey, params MySqlParameter[] commandParameters)
    {
        parmCache[cacheKey] = commandParameters;
    }

    /// <summary>
    /// get parameters in hashtable by cacheKey
    /// </summary>
    /// <param name="cacheKey">hashtable key name</param>
    /// <returns>the parameters</returns>
    public static MySqlParameter[] GetCachedParameters(string cacheKey)
    {
        MySqlParameter[] cachedParms = (MySqlParameter[])parmCache[cacheKey];

        if (cachedParms == null)
            return null;

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

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

        return clonedParms;
    }

    /// <summary>
    ///Prepare parameters for the implementation of the command
    /// </summary>
    /// <param name="cmd">mySqlCommand command</param>
    /// <param name="conn">database connection that is existing</param>
    /// <param name="trans">database transaction processing </param>
    /// <param name="cmdType">SqlCommand command type (stored procedures, T-SQL statement, and so on.) </param>
    /// <param name="cmdText">Command text, T-SQL statements such as Select * from Products</param>
    /// <param name="cmdParms">return the command that has parameters</param>
    private static void PrepareCommand(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;

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

        cmd.CommandType = cmdType;

        if (cmdParms != null)
            foreach (MySqlParameter parm in cmdParms)
                cmd.Parameters.Add(parm);
    }
    #region parameters
    /// <summary>
    /// Set parameters
    /// </summary>
    /// <param name="ParamName">parameter name</param>
    /// <param name="DbType">data type</param>
    /// <param name="Size">type size</param>
    /// <param name="Direction">input or output</param>
    /// <param name="Value">set the value</param>
    /// <returns>Return parameters that has been assigned</returns>
    public static MySqlParameter CreateParam(string ParamName, MySqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
    {
        MySqlParameter param;


        if (Size > 0)
        {
            param = new MySqlParameter(ParamName, DbType, Size);
        }
        else
        {

            param = new MySqlParameter(ParamName, DbType);
        }


        param.Direction = Direction;
        if (!(Direction == ParameterDirection.Output && Value == null))
        {
            param.Value = Value;
        }


        return param;
    }

    /// <summary>
    /// set Input parameters
    /// </summary>
    /// <param name="ParamName">parameter names, such as:@ id </param>
    /// <param name="DbType">parameter types, such as: MySqlDbType.Int</param>
    /// <param name="Size">size parameters, such as: the length of character type for the 100</param>
    /// <param name="Value">parameter value to be assigned</param>
    /// <returns>Parameters</returns>
    public static MySqlParameter CreateInParam(string ParamName, MySqlDbType DbType, int Size, object Value)
    {
        return CreateParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
    }

    /// <summary>
    /// Output parameters 
    /// </summary>
    /// <param name="ParamName">parameter names, such as:@ id</param>
    /// <param name="DbType">parameter types, such as: MySqlDbType.Int</param>
    /// <param name="Size">size parameters, such as: the length of character type for the 100</param>
    /// <param name="Value">parameter value to be assigned</param>
    /// <returns>Parameters</returns>
    public static MySqlParameter CreateOutParam(string ParamName, MySqlDbType DbType, int Size)
    {
        return CreateParam(ParamName, DbType, Size, ParameterDirection.Output, null);
    }

    /// <summary>
    /// Set return parameter value 
    /// </summary>
    /// <param name="ParamName">parameter names, such as:@ id</param>
    /// <param name="DbType">parameter types, such as: MySqlDbType.Int</param>
    /// <param name="Size">size parameters, such as: the length of character type for the 100</param>
    /// <param name="Value">parameter value to be assigned<</param>
    /// <returns>Parameters</returns>
    public static MySqlParameter CreateReturnParam(string ParamName, MySqlDbType DbType, int Size)
    {
        return CreateParam(ParamName, DbType, Size, ParameterDirection.ReturnValue, null);
    }

    /// <summary>
    /// Generate paging storedProcedure parameters
    /// </summary>
    /// <param name="CurrentIndex">CurrentPageIndex</param>
    /// <param name="PageSize">pageSize</param>
    /// <param name="WhereSql">query Condition</param>
    /// <param name="TableName">tableName</param>
    /// <param name="Columns">columns to query</param>
    /// <param name="Sort">sort</param>
    /// <returns>MySqlParameter collection</returns>
    public static MySqlParameter[] GetPageParm(int CurrentIndex, int PageSize, string WhereSql, string TableName, string Columns, Hashtable Sort)
    {
        MySqlParameter[] parm = { 
                                   MySqlHelper.CreateInParam("@CurrentIndex",  MySqlDbType.Int32,      4,      CurrentIndex    ),
                                   MySqlHelper.CreateInParam("@PageSize",      MySqlDbType.Int32,      4,      PageSize        ),
                                   MySqlHelper.CreateInParam("@WhereSql",      MySqlDbType.VarChar,  2500,    WhereSql        ),
                                   MySqlHelper.CreateInParam("@TableName",     MySqlDbType.VarChar,  20,     TableName       ),
                                   MySqlHelper.CreateInParam("@Column",        MySqlDbType.VarChar,  2500,    Columns         ),
                                   MySqlHelper.CreateInParam("@Sort",          MySqlDbType.VarChar,  50,     GetSort(Sort)   ),
                                   MySqlHelper.CreateOutParam("@RecordCount",  MySqlDbType.Int32,      4                       )
                                   };
        return parm;
    }
    /// <summary>
    /// Statistics data that in table
    /// </summary>
    /// <param name="TableName">table name</param>
    /// <param name="Columns">Statistics column</param>
    /// <param name="WhereSql">conditions</param>
    /// <returns>Set of parameters</returns>
    public static MySqlParameter[] GetCountParm(string TableName, string Columns, string WhereSql)
    {
        MySqlParameter[] parm = { 
                                   MySqlHelper.CreateInParam("@TableName",     MySqlDbType.VarChar,  20,     TableName       ),
                                   MySqlHelper.CreateInParam("@CountColumn",  MySqlDbType.VarChar,  20,     Columns         ),
                                   MySqlHelper.CreateInParam("@WhereSql",      MySqlDbType.VarChar,  250,    WhereSql        ),
                                   MySqlHelper.CreateOutParam("@RecordCount",  MySqlDbType.Int32,      4                       )
                                   };
        return parm;
    }
    /// <summary>
    /// Get the sql that is Sorted 
    /// </summary>
    /// <param name="sort"> sort column and values</param>
    /// <returns>SQL sort string</returns>
    private static string GetSort(Hashtable sort)
    {
        string str = "";
        int i = 0;
        if (sort != null && sort.Count > 0)
        {
            foreach (DictionaryEntry de in sort)
            {
                i++;
                str += de.Key + " " + de.Value;
                if (i != sort.Count)
                {
                    str += ",";
                }
            }
        }
        return str;
    }

    /// <summary>
    /// execute a trascation include one or more sql sentence(author:donne yin)
    /// </summary>
    /// <param name="connectionString"></param>
    /// <param name="cmdType"></param>
    /// <param name="cmdTexts"></param>
    /// <param name="commandParameters"></param>
    /// <returns>execute trascation result(success: true | fail: false)</returns>
    public static bool ExecuteTransaction(string connectionString, CommandType cmdType, string[] cmdTexts, params MySqlParameter[][] commandParameters)
    {
        MySqlConnection myConnection = new MySqlConnection(connectionString);       //get the connection object
        myConnection.Open();                                                        //open the connection
        MySqlTransaction myTrans = myConnection.BeginTransaction();                 //begin a trascation
        MySqlCommand cmd = new MySqlCommand();
        cmd.Connection = myConnection;
        cmd.Transaction = myTrans;

        try
        {
            for (int i = 0; i < cmdTexts.Length; i++)
            {
                PrepareCommand(cmd, myConnection, null, cmdType, cmdTexts[i], commandParameters[i]);
                cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
            }
            myTrans.Commit();
        }
        catch
        {
            myTrans.Rollback();
            return false;
        }
        finally
        {
            myConnection.Close();
        }
        return true;
    }
    #endregion
}

 

添加代码:

// add
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = "INSERT INTO `tb_baobei` (`tb_Name`,`tb_Price`,`tb_Image`,`tb_Url`)" +
        " VALUES(@tb_Name,@tb_Price,@tb_Image,@tb_Url);";
MySqlParameter[] commandParameters = new MySqlParameter[]{
    new MySqlParameter("@tb_Name",bb.Name),
    new MySqlParameter("@tb_Price",bb.Price.Trim()),
    new MySqlParameter("@tb_Image",bb.Image),
    new MySqlParameter("@tb_Url",bb.Url)
};
MySqlHelper.ExecuteNonQuery(CommandType.Text, MySqlHelper.ConnectionStringManager, sqlcom.CommandText, commandParameters);

 

查询代码:

public string Login(string email,string password){

            MySqlCommand sqlcom = new MySqlCommand();
            sqlcom.CommandText = "select * from common_members where email =@email";
            MySqlParameter commandParameters = new MySqlParameter("@email", email);
            MySqlDataReader reader = MYSQLHelper.ExecuteReader(MYSQLHelper.ConnectionStringManager, CommandType.Text, sqlcom.CommandText, commandParameters);
            if (reader.Read() == true)
            {
                string pwd = reader["password"].ToString();
                if (pwd.Equals(password))
                {
                    return "1";
                }else
                {
                    return "0";
                }
                
            }
            else
            {
                return "-1";
            }
        }

 

配置文件:

<add key="MySQLConnString" value="Server=localhost;Database=test1;Uid=test;Pwd=test;pooling=false;charset=utf8" />

 

MySqlHelper.cs和MySqlHelper.cs下载地址:http://pan.baidu.com/s/1jGBNq2E

 

 

 

 

img_fa0be433d68c8212b2b0b3b1a564ccb1.png
如果本文对你有所帮助,请打赏——1元就足够感动我:)
支付宝打赏 微信打赏
联系邮箱:intdb@qq.com
我的GitHub: https://github.com/vipstone
关注公众号: img_9bde0f31ac4a0eca10b1bd7414b78faf.png


作者: 王磊
出处: http://vipstone.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,请标明出处。

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
关系型数据库 MySQL
【Mysql】服务没有响应控制功能。 请键入 NET HELPMSG 2186 以获得更多的帮助。
解决方法: 1. 下载dll文件 https://www.aliyundrive.com/s/oV6GgghtPkN 2.将文件放置在mysql bin文件夹下 3. 重新启动Mysql,发现启动成功了!🚀
1161 1
|
7月前
|
关系型数据库 MySQL
cmd中输入net start mysql 提示:服务名无效或者MySQL正在启动 MySQL无法启动
cmd中输入net start mysql 提示:服务名无效或者MySQL正在启动 MySQL无法启动
|
7月前
|
关系型数据库 MySQL 数据库
Net Core备份MySQL数据库
Net Core备份MySQL数据库
92 2
|
7月前
|
关系型数据库 MySQL
报错Mysql:net start mysql 服务名无效
报错Mysql:net start mysql 服务名无效
475 0
|
SQL 关系型数据库 MySQL
【SQL异常】启动MySQL时发生系统错误的解决方法(net start mysql 发生系统错误 5。 拒绝访问)
【SQL异常】启动MySQL时发生系统错误的解决方法(net start mysql 发生系统错误 5。 拒绝访问)
580 1
|
关系型数据库 MySQL 数据库
NET连接MySQL数据库的CRUD
NET连接MySQL数据库的CRUD
167 0
NET连接MySQL数据库的CRUD
|
关系型数据库 MySQL Java
NET连接MySQL数据库
NET连接MySQL数据库
193 0
NET连接MySQL数据库
|
关系型数据库 MySQL 程序员
在 Windows 命令提示符下启动 MySQL:net start mysql 发生系统错误 5。 拒绝访问。解决方式小结
在 Windows 命令提示符下启动 MySQL:net start mysql 发生系统错误 5。 拒绝访问。解决方式小结
929 1
在 Windows 命令提示符下启动 MySQL:net start mysql 发生系统错误 5。 拒绝访问。解决方式小结
|
关系型数据库 MySQL 数据库
MySQL无法启动的问题->MySQL 服务正在启动 . MySQL 服务无法启动。服务没有报告任何错误。 请键入 NET HELPMSG 3534 以获得更多的帮助
注意以上的操作会清除数据库内容及已经创建的数据库用户,会生成一个新的用户root,此用户没有密码🐱‍🏍
421 0
MySQL无法启动的问题->MySQL 服务正在启动 . MySQL 服务无法启动。服务没有报告任何错误。 请键入 NET HELPMSG 3534 以获得更多的帮助
|
关系型数据库 MySQL
net start mysql 无法启动mysql解决方案之一【NET HELPMSG 3534】
net start mysql 无法启动mysql解决方案之一【NET HELPMSG 3534】
509 1
net start mysql 无法启动mysql解决方案之一【NET HELPMSG 3534】