Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载
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 = , 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 > )
{
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, , CurrentIndex ),
MySqlHelper.CreateInParam("@PageSize", MySqlDbType.Int32, , PageSize ),
MySqlHelper.CreateInParam("@WhereSql", MySqlDbType.VarChar, , WhereSql ),
MySqlHelper.CreateInParam("@TableName", MySqlDbType.VarChar, , TableName ),
MySqlHelper.CreateInParam("@Column", MySqlDbType.VarChar, , Columns ),
MySqlHelper.CreateInParam("@Sort", MySqlDbType.VarChar, , GetSort(Sort) ),
MySqlHelper.CreateOutParam("@RecordCount", MySqlDbType.Int32, )
};
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, , TableName ),
MySqlHelper.CreateInParam("@CountColumn", MySqlDbType.VarChar, , Columns ),
MySqlHelper.CreateInParam("@WhereSql", MySqlDbType.VarChar, , WhereSql ),
MySqlHelper.CreateOutParam("@RecordCount", MySqlDbType.Int32, )
};
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 = ;
if (sort != null && sort.Count > )
{
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 = ; 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 "";
}else
{
return "";
} }
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
Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载的更多相关文章
- 在.NET连接MySQL以及封装好的MySQLHelper.cs
1.首先上MySQL网站下驱动:http://www.mysql.com/products/connector/ 2.安装下载的安装包 3.我们在Visual Studio里创建一个Web Appli ...
- C#工具类MySqlHelper,基于MySql.Data.MySqlClient封装
源码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...
- C# 基于MySQL的数据层基类(MySQLHelper)
这里介绍下比较简单的方式,引用MySql.Data.dll然后添加一个MySqlHelper类来对MySql数据库进行访问和操作. 1.将MySql.Data.dll引用到你的项目中 下载地址:MyS ...
- C#连接Mysql数据库 MysqlHelper.cs文件
mysql.data.dll下载_c#连接mysql必要插件mysql.data.dll是C#操作MYSQL的驱动文件,是c#连接mysql必要插件,使c#语言更简洁的操作mysql数据库.当你的电脑 ...
- 自己封装的ASP.NET的MYSQL的数据库操作类
/** * 作者:牛腩 * 创建时间:2010年3月7日17时35分 * 类说明:对MYSQL数据库的操作类 */ using System; using System.Data; using MyS ...
- .NET 使用 MySql.Data.dll 动态库操作MySql的帮助类--MySqlHelper
.NET 使用 MySql.Data.dll 动态库操作MySql的帮助类--MySqlHelper 參考演示样例代码,例如以下所看到的: /// <summary> /// MySql ...
- C#操作SqlServer MySql Oracle通用帮助类
C#操作SqlServer MySql Oracle通用帮助类 [前言] 作为一款成熟的面向对象高级编程语言,C#在ADO.Net的支持上已然是做的很成熟,我们可以方便地调用ADO.Net操作各类关系 ...
- Util应用程序框架公共操作类(九):Lambda表达式扩展
上一篇对Lambda表达式公共操作类进行了一些增强,本篇使用扩展方法对Lambda表达式进行扩展. 修改Util项目的Extensions.Expression.cs文件,代码如下. using Sy ...
- Util应用程序框架公共操作类(八):Lambda表达式公共操作类(二)
前面介绍了查询的基础扩展,下面准备给大家介绍一些有用的查询封装手法,比如对日期范围查询,数值范围查询的封装等,为了支持这些功能,需要增强公共操作类. Lambda表达式公共操作类,我在前面已经简单介绍 ...
随机推荐
- coalesce函数用法
COALESCE函数会依次检查输入的参数,返回第一个不是NULL的参数,只有当传入COALESCE函数的所有的参数都是NULL的时候,函数才会返回NULL
- C++ 非阻塞套接字的使用 (1)
在维护代码的过程中,发现软件运行的CPU占用率居高不下,在4核的电脑上占用了25%的CPU.查阅资料的得知,这是可能是由于软件中出现了死循环. 经过对软件的一些测试,最终确定了死循环出现的位置——通讯 ...
- oracle表空间不足时的处理方法
由于数据文件路径下的空间不足或表空间不足时,需要更换或扩展或新增表空间时,以下简单介绍下几种处理方式(数据文件/opt/oracle/oradata/testdb.dbf,原大小为100M) 一.扩大 ...
- caffe 在window下编译(windows7, cuda8.0,matlab接口编译)
1. 环境:Windows7,Cuda8.0,显卡GTX1080,Matlab2016a,VS2013 (ps:老板说服务器要装windows系统,没办法,又要折腾一番,在VS下编译好像在cuda8. ...
- [leetcode 25]Reverse Nodes in k-Group
1 题目: Given a linked list, reverse the nodes of a linked list k at a time and return its modified li ...
- Golang通过Thrift框架完美实现跨语言调用
每种语言都有自己最擅长的领域,Golang 最适合的领域就是服务器端程序. 做为服务器端程序,需要考虑性能同时也要考虑与各种语言之间方便的通讯.采用http协议简单,但性能不高.采用TCP通讯,则需要 ...
- 使用mybatis访问sql server
原创文章转载请注明出处:@协思, http://zeeman.cnblogs.com mybatis作为一种半自动化的ORM工具,可以提供更大的灵活性,逐渐受到社区的欢迎. 官方下载地址是:https ...
- [ZigBee] 4、ZigBee基础实验——中断
前言 上一篇介绍了CC2530的IO的基础知识,并用LED的控制来展示如何配置并控制GPIO的输出,用KEY状态的读取实验来展示如何读取GPIO的状态.从上一节的KEY状态读取的代码看出是采用轮训方式 ...
- mysql --prompt
mysql --prompt修改命令行链接mysql时的提示符,shell脚本示例如下 #!/bin/bash in crm) cmd='mysql -h192.168.1.2 -uroot -pro ...
- vim添加或删除多行注释
一.多行注释的添加 1. vim的命令模式下(ESC 进入命令模式): 2. 按CTRL+V进入可视化模式(VISUAL BLOCK): 注意:vim命令模式下v进入的是visual模式,ctrl+v ...