需要有一个工具类:
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 = "Server=xxxxxxx;Database=91bx;Uid=xxxx;Pwd=xxxxx;pooling=false;charset=utf8"; //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());
///
/// Execute a SqlCommand command that does not return value, by appointed and specified connectionstring
/// The parameter list using parameters that in array forms
///
///
/// Usage example:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure,
/// "PublishOrders", new MySqlParameter("@prodid", 24));
///
/// a valid database connectionstring
/// MySqlCommand command type (stored procedures, T-SQL statement, and so on.)
/// stored procedure name or T-SQL statement
/// MySqlCommand to provide an array of parameters used in the list
/// 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;
}
}
///
/// Execute a SqlCommand command that does not return value, by appointed and specified connectionstring
/// The parameter list using parameters that in array forms
///
///
/// Usage example:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure,
/// "PublishOrders", new MySqlParameter("@prodid", 24));
///
/// MySqlCommand command type (stored procedures, T-SQL statement, and so on.)
/// a valid database connectionstring
/// stored procedure name or T-SQL statement
/// MySqlCommand to provide an array of parameters used in the list
/// Returns true or false
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();
}
}
}
///
/// Execute a SqlCommand command that does not return value, by appointed and specified connectionstring
/// Array of form parameters using the parameter list
///
/// connection
/// MySqlCommand command type (stored procedures, T-SQL statement, and so on.)
/// stored procedure name or T-SQL statement
/// MySqlCommand to provide an array of parameters used in the list
/// Returns a value that means number of rows affected
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;
}
///
/// Execute a SqlCommand command that does not return value, by appointed and specified connectionstring
/// Array of form parameters using the parameter list
///
/// sql Connection that has transaction
/// SqlCommand command type (stored procedures, T-SQL statement, and so on.)
/// stored procedure name or T-SQL statement
/// MySqlCommand to provide an array of parameters used in the list
/// Returns a value that means number of rows affected
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;
}
///
/// Call method of sqldatareader to read data
///
/// connectionstring
/// command type, such as using stored procedures: CommandType.StoredProcedure
/// stored procedure name or T-SQL statement
/// parameters
/// SqlDataReader type of data collection
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;
}
}
///
/// use the ExectueScalar to read a single result
///
/// connectionstring
/// command type, such as using stored procedures: CommandType.StoredProcedure
/// stored procedure name or T-SQL statement
/// parameters
/// a value in object type
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;
}
///
/// cache the parameters in the HashTable
///
/// hashtable key name
/// the parameters that need to cached
public static void CacheParameters(string cacheKey, params MySqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
///
/// get parameters in hashtable by cacheKey
///
/// hashtable key name
/// the parameters
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;
}
///
///Prepare parameters for the implementation of the command
///
/// mySqlCommand command
/// database connection that is existing
/// database transaction processing
/// SqlCommand command type (stored procedures, T-SQL statement, and so on.)
/// Command text, T-SQL statements such as Select * from Products
/// return the command that has parameters
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
///
/// Set parameters
///
/// parameter name
/// data type
/// type size
/// input or output
/// set the value
/// Return parameters that has been assigned
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;
}
///
/// set Input parameters
///
/// parameter names, such as:@ id
/// parameter types, such as: MySqlDbType.Int
/// size parameters, such as: the length of character type for the 100
/// parameter value to be assigned
/// Parameters
public static MySqlParameter CreateInParam(string ParamName, MySqlDbType DbType, int Size, object Value)
{
return CreateParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
}
///
/// Output parameters
///
/// parameter names, such as:@ id
/// parameter types, such as: MySqlDbType.Int
/// size parameters, such as: the length of character type for the 100
/// parameter value to be assigned
/// Parameters
public static MySqlParameter CreateOutParam(string ParamName, MySqlDbType DbType, int Size)
{
return CreateParam(ParamName, DbType, Size, ParameterDirection.Output, null);
}
///
/// Set return parameter value
///
/// parameter names, such as:@ id
/// parameter types, such as: MySqlDbType.Int
/// size parameters, such as: the length of character type for the 100
/// parameter value to be assigned<
/// Parameters
public static MySqlParameter CreateReturnParam(string ParamName, MySqlDbType DbType, int Size)
{
return CreateParam(ParamName, DbType, Size, ParameterDirection.ReturnValue, null);
}
///
/// Generate paging storedProcedure parameters
///
/// CurrentPageIndex
/// pageSize
/// query Condition
/// tableName
/// columns to query
/// sort
/// MySqlParameter collection
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;
}
///
/// Statistics data that in table
///
/// table name
/// Statistics column
/// conditions
/// Set of parameters
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;
}
///
/// Get the sql that is Sorted
///
/// sort column and values
/// SQL sort string
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;
}
///
/// execute a trascation include one or more sql sentence(author:donne yin)
///
///
///
///
///
/// execute trascation result(success: true | fail: false)
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
}
常用操作:
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
namespace wolame
{
public class UserManage
{
//发送短信验证码以登录,顺便自动注册
public string login_by_code(string tele)
{
MyLog.WriteLog("tele:" + tele);
string res = string.Empty;
Random ran = new Random();
int RandKey = ran.Next(1000, 9999);
string code = RandKey.ToString();
sendmsg send = new sendmsg();
res = send.send(tele, code);
//res = "{\"reason\": \"短信发送成功\",\"result\": {\"count\": 1,\"fee\": 1,\"sid\": \"17110219460122891\"},\"error_code\": 0}";
sendmsgresult rs = new sendmsgresult();
JObject job = JObject.Parse(res);
if(job == null)
{
return "parse error!";
}
rs.reason = job["reason"].ToString();
rs.error_code = job["error_code"].ToString();
rs.result.count = ((JObject)job["result"])["count"].ToString();
rs.result.fee = ((JObject)job["result"])["fee"].ToString();
rs.result.sid = ((JObject)job["result"])["sid"].ToString();
//保存结果到数据库
if (rs.error_code.Equals("0"))//成功
{
MyLog.WriteLog("code:" + code);
save_and_update(tele, code);
}
return res;
}
public void save_and_update(string tele, string code)
{
MyLog.WriteLog("save_and_update:" + tele);
string uid = get_uid_by_tele(tele);
if(uid==null || uid.Length<=0)
{
MyLog.WriteLog("createuser:" + tele);
createuser(tele);
}
//更新验证码
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = @"update wolame_user set authcode=@v_authcode where tele=@v_tele;";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_authcode", code),
new MySqlParameter("@v_tele",tele),
};
MySqlHelper.ExecuteNonQuery(CommandType.Text, MySqlHelper.ConnectionStringManager, sqlcom.CommandText, commandParameters);
}
public void createuser(string tele)
{
MyLog.WriteLog("enter createuser:" + tele);
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = "insert into wolame_user (uid, createdate,tele,pswd) values(@v_uid, @v_createdate,@v_tele,@v_pswd);";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_uid", 0),
new MySqlParameter("@v_createdate",DateTime.Now.ToString()),
new MySqlParameter("@v_tele",tele),
new MySqlParameter("@v_pswd",""),
};
MySqlHelper.ExecuteNonQuery(CommandType.Text, MySqlHelper.ConnectionStringManager, sqlcom.CommandText, commandParameters);
}
//获取验证码
public string getcode(string tele)
{
string uid = string.Empty;
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = @"select authcode from wolame_user where tele=@v_tele";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_tele", tele),
};
MySqlDataReader reader = MySqlHelper.ExecuteReader(MySqlHelper.ConnectionStringManager, CommandType.Text, sqlcom.CommandText, commandParameters);
if (reader.Read() == true)
{
uid = reader["authcode"].ToString();
}
return uid;
}
//根据用户手机号获取uid
public string get_uid_by_tele(string tele)
{
string uid = string.Empty;
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = @"select uid from wolame_user where tele=@v_tele";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_tele", tele),
};
MySqlDataReader reader = MySqlHelper.ExecuteReader(MySqlHelper.ConnectionStringManager, CommandType.Text, sqlcom.CommandText, commandParameters);
if (reader.Read() == true)
{
uid = reader["uid"].ToString();
}
return uid;
}
//用户注册,通过手机号和密码
public string register(string json)
{
string result = string.Empty;
register_result res = new register_result();
res.result = "0";
res.uid = "0";
res.ret_msg = "";
JObject obj = JObject.Parse(json);
if(obj == null)
{
return JsonConvert.SerializeObject(res);
}
string tele = obj["tele"].ToString();
string pswd = obj["pswd"].ToString();
//byte[] bytes = Convert.FromBase64String(pswd);
//pswd = Encoding.Default.GetString(bytes);
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = "insert into wolame_user (uid, createdate,tele,pswd) values(@v_uid, @v_createdate,@v_tele,@v_pswd);";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_uid", 0),
new MySqlParameter("@v_createdate",DateTime.Now.ToString()),
new MySqlParameter("@v_tele",tele),
new MySqlParameter("@v_pswd",pswd),
};
bool bRet = MySqlHelper.ExecuteNonQuery(CommandType.Text, MySqlHelper.ConnectionStringManager, sqlcom.CommandText, commandParameters);
if (bRet)
{
res.uid = get_uid_by_tele(tele);
res.result = "1";
}
result = JsonConvert.SerializeObject(res);
return result;
}
//用户通过密码登录
public string login_by_pswd(string json)
{
string uid = string.Empty;
JObject obj = JObject.Parse(json);
if (obj == null)
{
return "";
}
string tele = obj["tele"].ToString();
string pswd = obj["pswd"].ToString();
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = @"select uid from wolame_user where tele=@v_tele and pswd=@v_pswd";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_tele", tele),
new MySqlParameter("@v_pswd", pswd),
};
MySqlDataReader reader = MySqlHelper.ExecuteReader(MySqlHelper.ConnectionStringManager, CommandType.Text, sqlcom.CommandText, commandParameters);
if (reader.Read() == true)
{
update_last_active_time(tele);
uid = reader["uid"].ToString();
}
return uid;
}
public string setpassword(string json)
{
string result = string.Empty;
result = "0";
JObject obj = JObject.Parse(json);
if (obj == null)
{
return "0";
}
string tele = obj["tele"].ToString();
string pswd = obj["pswd"].ToString();
string name = obj["name"].ToString();
string sex = obj["sex"].ToString();
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = @"update wolame_user set pswd=@v_pswd,name=@v_name,sex=@v_sex where tele=@v_tele;";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_pswd", pswd),
new MySqlParameter("@v_name",name),
new MySqlParameter("@v_sex",sex),
new MySqlParameter("@v_tele",tele),
};
bool bRet = MySqlHelper.ExecuteNonQuery(CommandType.Text, MySqlHelper.ConnectionStringManager, sqlcom.CommandText, commandParameters);
if(bRet)
{
result = "1";
}
return result;
}
public void update_last_active_time(string tele)
{
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = @"update wolame_user set lastactive=@v_lastactive where tele=@v_tele;";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_lastactive",DateTime.Now.ToString()),
new MySqlParameter("@v_tele",tele),
};
MySqlHelper.ExecuteNonQuery(CommandType.Text, MySqlHelper.ConnectionStringManager, sqlcom.CommandText, commandParameters);
}
//用户通过密码登录
public string reset_pswd(string json)
{
string res = string.Empty;
return res;
}
public string getuser(string tele)
{
string result = string.Empty;
MySqlCommand sqlcom = new MySqlCommand();
sqlcom.CommandText = @"select * from wolame_user where tele=@v_tele";
MySqlParameter[] commandParameters = new MySqlParameter[]{
new MySqlParameter("@v_tele", tele),
};
MySqlDataReader reader = MySqlHelper.ExecuteReader(MySqlHelper.ConnectionStringManager, CommandType.Text, sqlcom.CommandText, commandParameters);
if (reader.Read() == true)
{
userinfo user = new userinfo();
user.uid = reader["uid"].ToString();
user.createdate = reader["createdate"].ToString();
user.tele = reader["tele"].ToString();
user.name = reader["name"].ToString();
user.pswd = reader["pswd"].ToString();
user.sex = reader["sex"].ToString();
user.pid = reader["pid"].ToString();
user.level = reader["level"].ToString();
user.type = reader["type"].ToString();
user.lastactive = reader["lastactive"].ToString();
user.token = reader["token"].ToString();
user.authcode = reader["authcode"].ToString();
result = JsonConvert.SerializeObject(user);
}
return result;
}
}
}
附带一个.net写日志的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace BgService
{
public class MyLog
{
public static void WriteLog(string msg)
{
string date = DateTime.Now.ToString("yyyyMMdd");
string path = HttpContext.Current.Server.MapPath("./log/");
//判断Log目录是否存在,不存在则创建
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + date + ".log";
//使用StreamWriter写日志,包含时间,错误路径,错误信息
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("-----------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "-----------------");
// sw.WriteLine(HttpContext.Current.Request.Url.ToString());
sw.WriteLine(msg);
sw.WriteLine("\r\n");
}
}
}
}