MysqlHelper 需要重写

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";
}
}

时间: 2025-01-05 05:36:41

MysqlHelper 需要重写的相关文章

java中的重写和重载

重写 在java中有很多的继承,继承下来的有变量.方法.在有一些子类要实现的方法中,方法名.传的参数.返回值跟父类中的方法一样,但具体实现又跟父类的不一样,这时候我们就需要重写父类的方法,就比如我们有一个类叫做Animals,Animals类中有一个叫做Call,然后我们继承Animals又生成了Cat类和Dog类,Cat和Dog也分别有自己特别的叫声,程序如下: 1 class Animals { 2 public void call() { 3 System.out.println("啊啊啊

Cento7+Nginx 之 URL重写

Cento7+Nginx  之  URL重写 我们前一篇文章写了一个Cento7+Nginx 反向代理实现多域名跳转,今天主要介绍一下Cento7+Nginx  之  URL重写, Hostname:A-S.IXMSOFT.COM IP:192.168.5.20 Role:Nginx server 我们首先准备安装Nginx仓库 Yum install http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.

重写js alert

Window.prototype.alert = function(){ //创建一个大盒子 var box = document.createElement("div"); //创建一个关闭按钮 var button = document.createElement("button"); //定义一个对象保存样式 var boxName = { width:"500px", height:"180px", backgroun

二:理解ASP.NET的运行机制(例:基于HttpHandler的URL重写)

url重写就是把一些类似article.aspx?id=28的路径重写成 article/28/这样的路径 当用户访问article/28/的时候我们通过asp.net把这个请求重定向到article.aspx?id=28路径有两种方法可以做这件事情 一:基于HttpModule的方案这个方案有有缺点,具体缺点以后再谈我曾写过一篇文章<不用组件的url重写(适用于较大型项目) >就是按这个模式写的 二:基于HttpHandler的方案我们这个例子就是按这个方案做的我们接下来就按这种方式做这个例

在IIS 中如何配置URL Rewrite,并且利用出站规则保持被重写的Cookie的域

Url Rewrite配置 xx.aa.com/bb/test1.aspx 会重写到 bb.aa.com/test1.aspx 具体怎么配置入站 出站规则 结果:

PHP 方法重写override 与 抽象方法的实现之间的关系

重写由final关键字决定,但受父类的访问权限限制 实现基于继承,所以实现父类的抽象方法必须可访问到,父类抽象方法不可为private 1.父类某方法能否被子类重写与此方法的访问级别无关 public protected private对某方法内否被重写没有影响,能否被重写要看此方法是否被final修饰(final类不可被继承,final方法不可被重写) 2.但重写方法要受到访问级别的限制,即访问权限不可提升规定 (不仅仅是PHP,其他面向对象语言依然适用),访问权限只可以降低,不可以提升. 3

项目搭建系列之四:SpringMVC框架下使用UrlRewrite实现地址重写

简单记录一下UrlRewrite实现地址重写功能. 1.pom.xml 在pom.xml增加配置UrlRewrite jar <!-- URL Rewrite --> <dependency> <groupId>org.tuckey</groupId> <artifactId>urlrewritefilter</artifactId> <version>4.0.4</version> </dependen

重写equals和hashCode方法的示例

如果一个类有自己特有的"逻辑相等",且需要以此进行比较时,那么就需要重写equals方法. 在Object的规范中,重写equals方法有下面几条通用约定: 自反性. x.equals(x) == true 对称性.if   y.equals(x) == true , then  x.equals(y) == true 传递性.if   x.equals(y) == true y.equals(x) == true , then x.equals(z) == true 一致性.如果比较

Java中的方法重写 与 final关键字

Java中的方法重写 与 final关键字 以下程序是否存在错误? class Base { private final void method() { System.out.println("In Base..."); } } class Sub extends Base { public void method() { System.out.println("In Sub..."); } } 答案 正确的. 使用final关键字可以声明类.成员变量和成员方法,一