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

namespace Tools.Models
{
/// <summary>
/// when use mysql database application this class
/// Generic database access code
/// this class that is a abstract,which does not allow instantiation, the application can directly call it
/// </summary>
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 = 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
}
}
简单使用方法例子:

public String Reg(string email, string password, string nickname)
{
String ip = CommonFunction.getIP();
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = "INSERT INTO `common_members` (`uid`, `email`, `password`, `privilege`, `emailstatus`, `regtime`, `regip`, `lastloginip`, `lastlogintime`, `salt`, `nickname`, `avater`, `token`)" +
" VALUES(NULL, @email, @password, 1, 0,NOW(), @regip, @loginip, NOW(), 'asda22', @nickname, NULL, '');";

MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@email",email),
new MySqlParameter("@password",password),
new MySqlParameter("@nickname",nickname),
new MySqlParameter("@regip",ip),
new MySqlParameter("@loginip",ip)
};

bool res = MYSQLHelper.ExecuteNonQuery(CommandType.Text, MYSQLHelper.ConnectionStringManager, sqlcom.CommandText, commandParameters);
if (res == true)
{
return "1";
}
else
{
return "0";
}
}

MysqlHelper 需要重写的更多相关文章

  1. .NET 基础 一步步 一幕幕[面向对象之方法、方法的重载、方法的重写、方法的递归]

    方法.方法的重载.方法的重写.方法的递归 方法: 将一堆代码进行重用的一种机制. 语法: [访问修饰符] 返回类型 <方法名>(参数列表){ 方法主体: } 返回值类型:如果不需要写返回值 ...

  2. category中重写方法?

    问:可以在category中重写方法吗? 答:代码上可以实现 在category中重写方法,但在实际开发中,不建议这样做.如果确实需要重写原有方法也建议使用子类进行重写. category是为了更方便 ...

  3. ASP.NET Aries 4.0 开源发布:已完成基础功能优化重写

    主要更新: 1:增加AR.Global.GetUser() 方法返回当前登陆者的用户信息. 2:重写AR.Combobox 支持下拉树. 3:调整及扩展Input下拉的配置参数. 4:优化及新增AR. ...

  4. 小丁带你走进git的世界四-重写历史记录

    一.git对象文件创建 开篇先补充一个知识点,就是比如我建立一个文件之后,使用git add就会生成一个git对象,但是git对象生成后可以在.git/objects里面对应,首先我们来初始化一个仓库 ...

  5. 已经重写,源码和文章请跳转http://www.cnblogs.com/ymnets/p/5621706.html

    文章由于写得比较仓促 已经重写,源码和文章请跳转 http://www.cnblogs.com/ymnets/p/5621706.html 系列目录 前言: 导入导出实在多例子,很多成熟的组建都分装了 ...

  6. C#基础回顾(二)—页面值传递、重载与重写、类与结构体、装箱与拆箱

    一.前言 -孤独的路上有梦想作伴,乘风破浪- 二.页面值传递 (1)C#各页面之间可以进行数据的交换和传递,页面之间可根据获取的数据,进行各自的操作(跳转.计算等操作).为了实现多种方式的数据传递,C ...

  7. SQL Server索引视图以(物化视图)及索引视图与查询重写

    本位出处:http://www.cnblogs.com/wy123/p/6041122.html 经常听Oracle的同学说起来物化视图,物化视图的作用之一就是可以实现查询重写,听起来有一种高大上的感 ...

  8. Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详解

    转载:http://freeloda.blog.51cto.com/2033581/1288553 大纲 一.前言 二.环境准备 三.安装与配置Nginx 四.Nginx之反向代理 五.Nginx之负 ...

  9. Storm中遇到的日志多次重写问题(一)

    业务描述: 统计从kafka spout中读取的数据条数,以及写入redis的数据的条数,写入hdfs的数据条数,写入kafaka的数据条数.并且每过5秒将数据按照json文件的形式写入日志.其中保存 ...

随机推荐

  1. 浅谈被加壳ELF(即android的so文件)的调试

    本文只讨论如何调试被加壳的ELF文件,包括调试中的技巧运用及调试过程中可能遇到的问题的解决方法,不包含如何还原加固的DEX本文将以某加壳程序和某加固为目标. 一.ELF格式简介 ELF全称:Execu ...

  2. iOS开发之多媒体API (转载)

    视频格式可以分为适合本地播放的本地影像视频和适合在网络中播放的网络流媒体影像视频两大类.尽管后者在播放的稳定性和播放画面质量上可能没有前者 优秀,但网络流媒体影像视频的广泛传播性使之正被广泛应用于视频 ...

  3. Android JNI 和 NDK

    1.Android NDK 一.NDK产生的背景 Android平台从诞生起,就已经支持C.C++开发.众所周知,Android的SDK基于Java实现,这意味着基于Android SDK进行开发的第 ...

  4. iOS沙盒目录结构解析

    iOS沙盒目录结构解析 原文地址:http://blog.csdn.net/wzzvictory/article/details/18269713     出于安全考虑,iOS系统的沙盒机制规定每个应 ...

  5. windows 常用命令

    1 Services.msc  在运行输入 启动所有安装程序配置

  6. unity3D 常用快捷键

    http://blog.csdn.net/ganlijianstyle/article/details/7985509 此页面提供了Unity3D默认的快捷键. shift +方向键         ...

  7. Android Build Error(1)

    Type 1 —— Build Path Problem : **.jar包文件缺失 1.在Android项目根目录下新建一个libs文件夹: 2.把你需要的导入的第三方Jar包复制进这个目录: 3. ...

  8. Adobe Flash player 10 提示:Error#2044:未处理的IOErrorEvent. text=Error#2036:加载未完成 的解决方法

    在“我的电脑”上单击鼠标右键,选择管理,在管理窗口的左栏中打开“服务和应用程序”,点击“服务”,在右边窗口中双击打开名称为“Smart Card”的服务,“常规”->“启动类型”选为自动,“登录 ...

  9. 视频分享:过五关斩六将——我要做IT面霸!

    这是我在某网站分享的网络直播课程,现在博客园分享给大家! 本视频适合以下朋友观看: 1)在校计算机及相关专业学生,希望你了解应聘的要求后来改善你的学习: 2)正在求职或打算跳槽的人士: 3)HR或公司 ...

  10. IIS与Apache共用80端口方法

    IIS与Apache共用80端口 http://www.cnblogs.com/haocool/p/3595282.html Windows server 2003服务器上安装有默认 IIS 6和Ap ...