首页 > 代码库 > C# 各种帮助类大全
C# 各种帮助类大全
前言
此篇专门记录一些常见DB帮助类及其他帮助类,以便使用时不用重复造轮子。
DBHelper帮助类
①首当其冲的就是Sql Server帮助类,创建名为DbHelperSQL 的类 ,全部代码如下:
/// <summary> /// 数据访问抽象基础类 /// Copyright (C) Maticsoft /// </summary> public abstract class DbHelperSQL { //数据库连接字符串(web.config来配置),多数据库可使用DbHelperSQLP来实现. public static string connectionString = PubConstant.ConnectionString; public DbHelperSQL() { } #region 公用方法 /// <summary> /// 判断是否存在某表的某个字段 /// </summary> /// <param name="tableName">表名称</param> /// <param name="columnName">列名称</param> /// <returns>是否存在</returns> public static bool ColumnExists(string tableName, string columnName) { string sql = "select count(1) from syscolumns where [id]=object_id(‘" + tableName + "‘) and [name]=‘" + columnName + "‘"; object res = GetSingle(sql); if (res == null) { return false; } return Convert.ToInt32(res) > 0; } public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); //也可能=0 } if (cmdresult == 0) { return false; } else { return true; } } /// <summary> /// 表是否存在 /// </summary> /// <param name="TableName"></param> /// <returns></returns> public static bool TabExists(string TableName) { string strsql = "select count(*) from sysobjects where id = object_id(N‘[" + TableName + "]‘) and OBJECTPROPERTY(id, N‘IsUserTable‘) = 1"; //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N‘[dbo].[" + TableName + "]‘) AND type in (N‘U‘)"; object obj = GetSingle(strsql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql, params SqlParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } public static int ExecuteSqlByTime(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行Sql和Oracle滴混合事务 /// </summary> /// <param name="list">SQL命令行列表</param> /// <param name="oracleCmdSqlList">Oracle命令行列表</param> /// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns> public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { foreach (CommandInfo myDE in list) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; PrepareCommand(cmd, conn, tx, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.SolicitationEvent) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { tx.Rollback(); throw new Exception("违背要求"+myDE.CommandText+"必须符合select count(..的格式"); //return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (isHave) { //引发事件 myDE.OnSolicitationEvent(); } } if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式"); //return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0"); //return 0; } if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0"); //return 0; } continue; } int val = cmd.ExecuteNonQuery(); if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行"); //return 0; } cmd.Parameters.Clear(); } string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC"); bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList); if (!res) { tx.Rollback(); throw new Exception("Oracle执行失败"); // return -1; } tx.Commit(); return 1; } catch (System.Data.SqlClient.SqlException e) { tx.Rollback(); throw e; } catch (Exception e) { tx.Rollback(); throw e; } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static int ExecuteSqlTran(List<String> SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return 0; } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, string content) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static object ExecuteSqlGet(string SQLString, string content) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(strSQL, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } public static object GetSingle(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static SqlDataReader ExecuteReader(string strSQL) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(strSQL, connection); try { connection.Open(); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static void ExecuteSqlTran(Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int count = 0; //循环 foreach (CommandInfo myDE in cmdList) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { trans.Rollback(); return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) { trans.Rollback(); return 0; } if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) { trans.Rollback(); return 0; } continue; } int val = cmd.ExecuteNonQuery(); count += val; if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) { trans.Rollback(); return 0; } cmd.Parameters.Clear(); } trans.Commit(); return count; } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int indentity = 0; //循环 foreach (CommandInfo myDE in SQLStringList) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int indentity = 0; //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } /// <summary> /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } // finally // { // cmd.Dispose(); // connection.Close(); // } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } } private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (SqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } #endregion #region 存储过程操作 /// <summary> /// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlDataReader</returns> public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SqlConnection connection = new SqlConnection(connectionString); SqlDataReader returnReader; connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); return returnReader; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="tableName">DataSet结果中的表名</param> /// <returns>DataSet</returns> public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.SelectCommand.CommandTimeout = Times; sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } /// <summary> /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand</returns> private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SqlParameter parameter in parameters) { if (parameter != null) { // 检查未分配值的输出参数,将其分配以DBNull.Value. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } return command; } /// <summary> /// 执行存储过程,返回影响的行数 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="rowsAffected">影响的行数</param> /// <returns></returns> public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (SqlConnection connection = new SqlConnection(connectionString)) { int result; connection.Open(); SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); result = (int)command.Parameters["ReturnValue"].Value; //Connection.Close(); return result; } } /// <summary> /// 创建 SqlCommand 对象实例(用来返回一个整数值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand 对象实例</returns> private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } #endregion }
注意:根据提示引用相关命名空间即可。
上述代码中用到了一个PubConstant类 用来获取连接字符串,全部代码如下:
public class PubConstant { /// <summary> /// 获取连接字符串 /// </summary> public static string ConnectionString { get { string _connectionString = ConfigurationManager.AppSettings["ConnectionString"]; string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"]; if (ConStringEncrypt == "true") { _connectionString = DESEncrypt.Decrypt(_connectionString); } return _connectionString; } } /// <summary> /// 得到web.config里配置项的数据库连接字符串。 /// </summary> /// <param name="configName"></param> /// <returns></returns> public static string GetConnectionString(string configName) { string connectionString = ConfigurationManager.AppSettings[configName]; string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"]; if (ConStringEncrypt == "true") { connectionString = DESEncrypt.Decrypt(connectionString); } return connectionString; } }
PubConstant类中对连接字符串进行了DES加密解密操作,DES加密/解密帮助类全部代码如下:
/// <summary> /// DES加密/解密类。 /// </summary> public class DESEncrypt { public DESEncrypt() { } #region ========加密======== /// <summary> /// 加密 /// </summary> /// <param name="Text"></param> /// <returns></returns> public static string Encrypt(string Text) { return Encrypt(Text, "MATICSOFT"); } /// <summary> /// 加密数据 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Encrypt(string Text,string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray; inputByteArray=Encoding.Default.GetBytes(Text); des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); System.IO.MemoryStream ms=new System.IO.MemoryStream(); CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret=new StringBuilder(); foreach( byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}",b); } return ret.ToString(); } #endregion #region ========解密======== /// <summary> /// 解密 /// </summary> /// <param name="Text"></param> /// <returns></returns> public static string Decrypt(string Text) { return Decrypt(Text, "MATICSOFT"); } /// <summary> /// 解密数据 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Decrypt(string Text,string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); int len; len=Text.Length/2; byte[] inputByteArray = new byte[len]; int x,i; for(x=0;x<len;x++) { i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); inputByteArray[x]=(byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); System.IO.MemoryStream ms=new System.IO.MemoryStream(); CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); } #endregion }
强烈建议使用ESC加密
全部代码如下:
public class DESCrypto { private static string key = "KABCMS2017"; /// <summary> /// 加密(UTF-8) /// </summary> /// <param name="str">待加密字符串</param> /// <param name="secKey">密钥(长度不能少于8位字符)</param> /// <returns></returns> public static string Encode(string str, string secKey = "") { if (string.IsNullOrEmpty(secKey)) secKey = key; else if (secKey.Length < 8) return ""; DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); provider.Key = Encoding.ASCII.GetBytes(secKey.Substring(0, 8)); provider.IV = Encoding.ASCII.GetBytes(secKey.Substring(0, 8)); byte[] bytes = Encoding.GetEncoding("UTF-8").GetBytes(str); MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write); stream2.Write(bytes, 0, bytes.Length); stream2.FlushFinalBlock(); StringBuilder builder = new StringBuilder(); foreach (byte num in stream.ToArray()) { builder.AppendFormat("{0:X2}", num); } stream.Close(); return builder.ToString(); } /// <summary> /// 解密(UTF-8) /// </summary> /// <param name="str">待解密字符串</param> /// <param name="secKey">密钥(长度不能少于8位字符)</param> /// <returns></returns> public static string Decode(string str, string secKey = "") { if (string.IsNullOrEmpty(secKey)) secKey = key; else if (secKey.Length < 8) return ""; DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); provider.Key = Encoding.ASCII.GetBytes(secKey.Substring(0, 8)); provider.IV = Encoding.ASCII.GetBytes(secKey.Substring(0, 8)); byte[] buffer = new byte[str.Length / 2]; for (int i = 0; i < (str.Length / 2); i++) { int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10); buffer[i] = (byte)num2; } MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write); stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); stream.Close(); return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray()); } }
然后再配置文件中新建几个字符串链接,分别连接不同的库,代码如下:
<add key="ConnectionString1" value=http://www.mamicode.com/"Server=.;Database=数据库名;Uid=账号;Pwd=密码;allow zero datetime = true" /> -- MySql <add key="ConnectionString" value=http://www.mamicode.com/"Server=.;Database=数据库名;Uid=账号;Pwd=密码;" /> -- SqlServer <add key="ConnectionString11" value=http://www.mamicode.com/"Provider=SQLOLEDB;Server=.;Initial Catalog=数据库名;Uid=账号;Pwd=密码;" /> -- SqlLole
使用
/// <summary> /// 根据账号获取信息 /// </summary> /// <param name="name"></param> /// <returns></returns> public ServiceProvider GetNameByQR(string name) { try { string sql = "select 字段1, 字段2, 字段3 from viw_promotion where name=‘" + name + "‘"; DataSet ds = DbHelperMySQL.Query(sql);//此处调用MysqlDBHelper帮助类 DataTable dt = ds.Tables[0]; ServiceProvider ProviderQR = new ServiceProvider(); foreach (DataRow item in dt.Rows) { if (!string.IsNullOrEmpty(item["字段1"].ToString())) { ProviderQR.PropertName = item["字段1"].ToString(); } if (!string.IsNullOrEmpty(item["字段2"].ToString())) { ProviderQR.PropertyURL = item["字段2"].ToString(); } if (!string.IsNullOrEmpty(item["字段3"].ToString())) { ProviderQR.PropertyQRCode = item["字段3"].ToString(); } } return ProviderQR; //返回实体对象 } catch (Exception) { return null; } }
② DbHelperMySQL帮助类,全部代码如下:
/// <summary> /// 数据访问抽象基础类 /// Copyright (C) Maticsoft /// </summary> public abstract class DbHelperMySQL { //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. // public static string connectionString = PubConstant.ConnectionString;Mysql_ConnectionString,ConnectionString1 public static string connectionString = ConfigurationManager.AppSettings["ConnectionString1"]; public DbHelperMySQL() { } #region 公用方法 /// <summary> /// 得到最大值 /// </summary> /// <param name="FieldName"></param> /// <param name="TableName"></param> /// <returns></returns> public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } /// <summary> /// 是否存在 /// </summary> /// <param name="strSql"></param> /// <returns></returns> public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } /// <summary> /// 是否存在(基于MySqlParameter) /// </summary> /// <param name="strSql"></param> /// <param name="cmdParms"></param> /// <returns></returns> public static bool Exists(string strSql, params MySqlParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw e; } } } } public static int ExecuteSqlByTime(string SQLString, int Times) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; int rows = cmd.ExecuteNonQuery(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行MySql和Oracle滴混合事务 /// </summary> /// <param name="list">SQL命令行列表</param> /// <param name="oracleCmdSqlList">Oracle命令行列表</param> /// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns> public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; MySqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { foreach (CommandInfo myDE in list) { string cmdText = myDE.CommandText; MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters; PrepareCommand(cmd, conn, tx, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.SolicitationEvent) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { tx.Rollback(); throw new Exception("违背要求"+myDE.CommandText+"必须符合select count(..的格式"); //return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (isHave) { //引发事件 myDE.OnSolicitationEvent(); } } if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式"); //return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0"); //return 0; } if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0"); //return 0; } continue; } int val = cmd.ExecuteNonQuery(); if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行"); //return 0; } cmd.Parameters.Clear(); } string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC"); bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList); if (!res) { tx.Rollback(); throw new Exception("执行失败"); // return -1; } tx.Commit(); return 1; } catch (MySql.Data.MySqlClient.MySqlException e) { tx.Rollback(); throw e; } catch (Exception e) { tx.Rollback(); throw e; } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static int ExecuteSqlTran(List<String> SQLStringList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; MySqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return 0; } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, string content) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(SQLString, connection); MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static object ExecuteSqlGet(string SQLString, string content) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(SQLString, connection); MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(strSQL, connection); MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw e; } } } } public static object GetSingle(string SQLString, int Times) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw e; } } } } /// <summary> /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>MySqlDataReader</returns> public static MySqlDataReader ExecuteReader(string strSQL) { MySqlConnection connection = new MySqlConnection(connectionString); MySqlCommand cmd = new MySqlCommand(strSQL, connection); try { connection.Open(); MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, int Times) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds, "ds"); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param> public static void ExecuteSqlTran(Hashtable SQLStringList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); using (MySqlTransaction trans = conn.BeginTransaction()) { MySqlCommand cmd = new MySqlCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param> public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); using (MySqlTransaction trans = conn.BeginTransaction()) { MySqlCommand cmd = new MySqlCommand(); try { int count = 0; //循环 foreach (CommandInfo myDE in cmdList) { string cmdText = myDE.CommandText; MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { trans.Rollback(); return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) { trans.Rollback(); return 0; } if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) { trans.Rollback(); return 0; } continue; } int val = cmd.ExecuteNonQuery(); count += val; if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) { trans.Rollback(); return 0; } cmd.Parameters.Clear(); } trans.Commit(); return count; } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param> public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); using (MySqlTransaction trans = conn.BeginTransaction()) { MySqlCommand cmd = new MySqlCommand(); try { int indentity = 0; //循环 foreach (CommandInfo myDE in SQLStringList) { string cmdText = myDE.CommandText; MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters; foreach (MySqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (MySqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param> public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); using (MySqlTransaction trans = conn.BeginTransaction()) { MySqlCommand cmd = new MySqlCommand(); try { int indentity = 0; //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value; foreach (MySqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (MySqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString, params MySqlParameter[] cmdParms) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } } } } /// <summary> /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>MySqlDataReader</returns> public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms) { MySqlConnection connection = new MySqlConnection(connectionString); MySqlCommand cmd = new MySqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } // finally // { // cmd.Dispose(); // connection.Close(); // } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (MySqlDataAdapter da = new MySqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds; } } } private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, 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 = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (MySqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } #endregion }
注意,Mysql需要引入mysql.dll 点我下载
③ SQLite帮助类,全部代码如下:
/// <summary> /// Copyright (C) 2011 Maticsoft /// 数据访问基础类(基于SQLite) /// 可以用户可以修改满足自己项目的需要。 /// </summary> public abstract class DbHelperSQLite { //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. public static string connectionString = PubConstant.ConnectionString; public DbHelperSQLite() { } #region 公用方法 public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql, params SQLiteParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SQLite.SQLiteException E) { connection.Close(); throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static void ExecuteSqlTran(ArrayList SQLStringList) { using (SQLiteConnection conn = new SQLiteConnection(connectionString)) { conn.Open(); SQLiteCommand cmd = new SQLiteCommand(); cmd.Connection = conn; SQLiteTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n].ToString(); if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); } catch (System.Data.SQLite.SQLiteException E) { tx.Rollback(); throw new Exception(E.Message); } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, string content) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(SQLString, connection); SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SQLite.SQLiteException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(strSQL, connection); SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SQLite.SQLiteException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SQLite.SQLiteException e) { connection.Close(); throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回SQLiteDataReader /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SQLiteDataReader</returns> public static SQLiteDataReader ExecuteReader(string strSQL) { SQLiteConnection connection = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand(strSQL, connection); try { connection.Open(); SQLiteDataReader myReader = cmd.ExecuteReader(); return myReader; } catch (System.Data.SQLite.SQLiteException e) { throw new Exception(e.Message); } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SQLite.SQLiteException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (System.Data.SQLite.SQLiteException E) { throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SQLiteParameter[])</param> public static void ExecuteSqlTran(Hashtable SQLStringList) { using (SQLiteConnection conn = new SQLiteConnection(connectionString)) { conn.Open(); using (SQLiteTransaction trans = conn.BeginTransaction()) { SQLiteCommand cmd = new SQLiteCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); trans.Commit(); } } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString, params SQLiteParameter[] cmdParms) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { using (SQLiteCommand cmd = new SQLiteCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SQLite.SQLiteException e) { throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回SQLiteDataReader /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SQLiteDataReader</returns> public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms) { SQLiteConnection connection = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SQLiteDataReader myReader = cmd.ExecuteReader(); cmd.Parameters.Clear(); return myReader; } catch (System.Data.SQLite.SQLiteException e) { throw new Exception(e.Message); } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString, params SQLiteParameter[] cmdParms) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { SQLiteCommand cmd = new SQLiteCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SQLite.SQLiteException ex) { throw new Exception(ex.Message); } return ds; } } } private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (SQLiteParameter parm in cmdParms) cmd.Parameters.Add(parm); } } #endregion }
④Oracle帮助类,全部代码如下:
/// <summary> /// Copyright (C) Maticsoft /// 数据访问基础类(基于Oracle) /// 可以用户可以修改满足自己项目的需要。 /// </summary> public abstract class DbHelperOra { //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. public static string connectionString = PubConstant.ConnectionString; public DbHelperOra() { } #region 公用方法 public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql, params OracleParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (OracleConnection connection = new OracleConnection(connectionString)) { using (OracleCommand cmd = new OracleCommand(SQLString,connection)) { try { connection.Open(); int rows=cmd.ExecuteNonQuery(); return rows; } catch(System.Data.OracleClient.OracleException E) { connection.Close(); throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static void ExecuteSqlTran(ArrayList SQLStringList) { using (OracleConnection conn = new OracleConnection(connectionString)) { conn.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection=conn; OracleTransaction tx=conn.BeginTransaction(); cmd.Transaction=tx; try { for(int n=0;n<SQLStringList.Count;n++) { string strsql=SQLStringList[n].ToString(); if (strsql.Trim().Length>1) { cmd.CommandText=strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); } catch(System.Data.OracleClient.OracleException E) { tx.Rollback(); throw new Exception(E.Message); } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString,string content) { using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand cmd = new OracleCommand(SQLString,connection); System.Data.OracleClient.OracleParameter myParameter = new System.Data.OracleClient.OracleParameter("@content", OracleType.NVarChar); myParameter.Value = content ; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows=cmd.ExecuteNonQuery(); return rows; } catch(System.Data.OracleClient.OracleException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL,byte[] fs) { using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand cmd = new OracleCommand(strSQL,connection); System.Data.OracleClient.OracleParameter myParameter = new System.Data.OracleClient.OracleParameter("@fs", OracleType.LongRaw); myParameter.Value = fs ; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows=cmd.ExecuteNonQuery(); return rows; } catch(System.Data.OracleClient.OracleException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { using (OracleConnection connection = new OracleConnection(connectionString)) { using(OracleCommand cmd = new OracleCommand(SQLString,connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if((Object.Equals(obj,null))||(Object.Equals(obj,System.DBNull.Value))) { return null; } else { return obj; } } catch(System.Data.OracleClient.OracleException e) { connection.Close(); throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>OracleDataReader</returns> public static OracleDataReader ExecuteReader(string strSQL) { OracleConnection connection = new OracleConnection(connectionString); OracleCommand cmd = new OracleCommand(strSQL,connection); try { connection.Open(); OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch(System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { using (OracleConnection connection = new OracleConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); OracleDataAdapter command = new OracleDataAdapter(SQLString,connection); command.Fill(ds,"ds"); } catch(System.Data.OracleClient.OracleException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString,params OracleParameter[] cmdParms) { using (OracleConnection connection = new OracleConnection(connectionString)) { using (OracleCommand cmd = new OracleCommand()) { try { PrepareCommand(cmd, connection, null,SQLString, cmdParms); int rows=cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch(System.Data.OracleClient.OracleException E) { throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param> public static void ExecuteSqlTran(Hashtable SQLStringList) { using (OracleConnection conn = new OracleConnection(connectionString)) { conn.Open(); using (OracleTransaction trans = conn.BeginTransaction()) { OracleCommand cmd = new OracleCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText=myDE.Key.ToString(); OracleParameter[] cmdParms=(OracleParameter[])myDE.Value; PrepareCommand(cmd,conn,trans,cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); trans.Commit(); } } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString,params OracleParameter[] cmdParms) { using (OracleConnection connection = new OracleConnection(connectionString)) { using (OracleCommand cmd = new OracleCommand()) { try { PrepareCommand(cmd, connection, null,SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if((Object.Equals(obj,null))||(Object.Equals(obj,System.DBNull.Value))) { return null; } else { return obj; } } catch(System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>OracleDataReader</returns> public static OracleDataReader ExecuteReader(string SQLString,params OracleParameter[] cmdParms) { OracleConnection connection = new OracleConnection(connectionString); OracleCommand cmd = new OracleCommand(); try { PrepareCommand(cmd, connection, null,SQLString, cmdParms); OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch(System.Data.OracleClient.OracleException e) { throw new Exception(e.Message); } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString,params OracleParameter[] cmdParms) { using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, connection, null,SQLString, cmdParms); using( OracleDataAdapter da = new OracleDataAdapter(cmd) ) { DataSet ds = new DataSet(); try { da.Fill(ds,"ds"); cmd.Parameters.Clear(); } catch(System.Data.OracleClient.OracleException ex) { throw new Exception(ex.Message); } return ds; } } } private static void PrepareCommand(OracleCommand cmd,OracleConnection conn,OracleTransaction trans, string cmdText, OracleParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (OracleParameter parm in cmdParms) cmd.Parameters.Add(parm); } } #endregion #region 存储过程操作 /// <summary> /// 执行存储过程 返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleDataReader</returns> public static OracleDataReader RunProcedure(string storedProcName, IDataParameter[] parameters ) { OracleConnection connection = new OracleConnection(connectionString); OracleDataReader returnReader; connection.Open(); OracleCommand command = BuildQueryCommand( connection,storedProcName, parameters ); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); return returnReader; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="tableName">DataSet结果中的表名</param> /// <returns>DataSet</returns> public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName ) { using (OracleConnection connection = new OracleConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); OracleDataAdapter sqlDA = new OracleDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters ); sqlDA.Fill( dataSet, tableName ); connection.Close(); return dataSet; } } /// <summary> /// 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleCommand</returns> private static OracleCommand BuildQueryCommand(OracleConnection connection,string storedProcName, IDataParameter[] parameters) { OracleCommand command = new OracleCommand( storedProcName, connection ); command.CommandType = CommandType.StoredProcedure; foreach (OracleParameter parameter in parameters) { command.Parameters.Add( parameter ); } return command; } /// <summary> /// 执行存储过程,返回影响的行数 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="rowsAffected">影响的行数</param> /// <returns></returns> public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected ) { using (OracleConnection connection = new OracleConnection(connectionString)) { int result; connection.Open(); OracleCommand command = BuildIntCommand(connection,storedProcName, parameters ); rowsAffected = command.ExecuteNonQuery(); result = (int)command.Parameters["ReturnValue"].Value; //Connection.Close(); return result; } } /// <summary> /// 创建 OracleCommand 对象实例(用来返回一个整数值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleCommand 对象实例</returns> private static OracleCommand BuildIntCommand(OracleConnection connection,string storedProcName, IDataParameter[] parameters) { OracleCommand command = BuildQueryCommand(connection,storedProcName, parameters ); command.Parameters.Add( new OracleParameter ( "ReturnValue", OracleType.Int32, 4, ParameterDirection.ReturnValue, false,0,0,string.Empty,DataRowVersion.Default,null )); return command; } #endregion }
⑤缓存帮助类,全部代码如下:
using System.Web.Caching; public class WebDataCache { /// <summary> /// 获取当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"></param> /// <returns></returns> public static object GetCache(string CacheKey) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; return objCache[CacheKey]; } /// <summary> /// 删除当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"></param> /// <returns></returns> public static object RemoveCache(string CacheKey) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; return objCache.Remove(CacheKey); } /// <summary> /// 设置当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"></param> /// <param name="objObject"></param> public static void SetCache(string CacheKey, object objObject) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject); } /// <summary> /// 设置当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"></param> /// <param name="objObject"></param> public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration); } /// <summary> /// 设置当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"></param> /// <param name="objObject"></param> /// <param name="absoluteExpiration">设置绝对过期时间</param> public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject, null, absoluteExpiration, Cache.NoSlidingExpiration); } /// <summary> /// 设置当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"></param> /// <param name="objObject"></param> /// <param name="slidingExpiration">设置滑动过期时间</param> public static void SetCache(string CacheKey, object objObject, TimeSpan slidingExpiration) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject, null, Cache.NoAbsoluteExpiration, slidingExpiration); } }
使用方式:
例如,登陆的时候可以先获取是否有该缓存:
if (WebDataCache.GetCache(userName + "固定标识符") == null) { 实体对象= _roles.UserRolesOperS(userName);//根据用户名查询出用户权限 赋值到实体中 WebDataCache.SetCache(userName + "固定标识符", UserRolesOper, DateTime.Now.AddSeconds(double.Parse(ConfigurationManager.AppSettings["Cache"].ToString())));//设置缓存过期时间,在配置文件中配置
}
清空缓存操作:
WebDataCache.RemoveCache(User_Name + "_MenuAction");//清空缓存
缓存为空或过期需重新查出
使用缓存:
object obj = WebDataCache.GetCache(userName + "固定标识符");
var userRoleOper = (List<实体对象>)obj; //
⑥字符串加密组件
/// <summary> /// 字符串加密组件 /// </summary> public class Encrypt { #region "定义加密字串变量" private SymmetricAlgorithm mCSP; //声明对称算法变量 private const string CIV = "Mi9l/+7Zujhy12se6Yjy111A"; //初始化向量 private const string CKEY = "jkHuIy9D/9i="; //密钥(常量) #endregion /// <summary> /// 实例化 /// </summary> public Encrypt() { mCSP = new DESCryptoServiceProvider(); //定义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象,此类是SymmetricAlgorithm的派生类 } /// <summary> /// 加密字符串 /// </summary> /// <param name="Value">需加密的字符串</param> /// <returns></returns> public string EncryptString(string Value) { ICryptoTransform ct; //定义基本的加密转换运算 MemoryStream ms; //定义内存流 CryptoStream cs; //定义将内存流链接到加密转换的流 byte[] byt; //CreateEncryptor创建(对称数据)加密对象 ct = mCSP.CreateEncryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV)); //用指定的密钥和初始化向量创建对称数据加密标准 byt = Encoding.UTF8.GetBytes(Value); //将Value字符转换为UTF-8编码的字节序列 ms = new MemoryStream(); //创建内存流 cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); //将内存流链接到加密转换的流 cs.Write(byt, 0, byt.Length); //写入内存流 cs.FlushFinalBlock(); //将缓冲区中的数据写入内存流,并清除缓冲区 cs.Close(); //释放内存流 return Convert.ToBase64String(ms.ToArray()); //将内存流转写入字节数组并转换为string字符 } /// <summary> /// 解密字符串 /// </summary> /// <param name="Value">要解密的字符串</param> /// <returns>string</returns> public string DecryptString(string Value) { ICryptoTransform ct; //定义基本的加密转换运算 MemoryStream ms; //定义内存流 CryptoStream cs; //定义将数据流链接到加密转换的流 byte[] byt; ct = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV)); //用指定的密钥和初始化向量创建对称数据解密标准 byt = Convert.FromBase64String(Value); //将Value(Base 64)字符转换成字节数组 ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Encoding.UTF8.GetString(ms.ToArray()); //将字节数组中的所有字符解码为一个字符串 } /// <summary> /// 生成随机数 /// </summary> /// <param name="num"></param> /// <returns></returns> public string GetMixPwd(int num)//生成混合随机数 { string a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; StringBuilder sb = new StringBuilder(); for (int i = 0; i < num; i++) { sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]); } return sb.ToString(); } }
⑦ 输入汉字获取拼音或首字母大写 新建类 ConvertHzToPy,全部代码如下:
/// <summary>/// Summary description for ConvertHzToPz_Gb2312/// </summary>public class ConvertHzToPy{ public ConvertHzToPy() { // // TODO: Add constructor logic here // } private static int[] pyvalue = http://www.mamicode.com/new int[]{-20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,-20032,-20026, -20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,-19756,-19751,-19746,-19741,-19739,-19728, -19725,-19715,-19540,-19531,-19525,-19515,-19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263, -19261,-19249,-19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,-19003,-18996, -18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,-18731,-18722,-18710,-18697,-18696,-18526, -18518,-18501,-18490,-18478,-18463,-18448,-18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012,-17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,-17733,-17730, -17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,-17468,-17454,-17433,-17427,-17417,-17202, -17185,-16983,-16970,-16942,-16915,-16733,-16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459, -16452,-16448,-16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216,-16212,-16205, -16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,-15933,-15920,-15915,-15903,-15889,-15878, -15707,-15701,-15681,-15667,-15661,-15659,-15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416, -15408,-15394,-15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150,-15149,-15144, -15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109,-14941,-14937,-14933,-14930,-14929,-14928, -14926,-14922,-14921,-14914,-14908,-14902,-14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668, -14663,-14654,-14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345,-14170,-14159, -14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112,-14109,-14099,-14097,-14094,-14092,-14090, -14087,-14083,-13917,-13914,-13910,-13907,-13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658, -13611,-13601,-13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343,-13340,-13329, -13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076,-13068,-13063,-13060,-12888,-12875,-12871, -12860,-12858,-12852,-12849,-12838,-12831,-12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346, -12320,-12300,-12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798,-11781,-11604, -11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067,-11055,-11052,-11045,-11041,-11038,-11024, -11020,-11019,-11018,-11014,-10838,-10832,-10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331, -10329,-10328,-10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254}; private static string[] pystr = new string[]{"a","ai","an","ang","ao","ba","bai","ban","bang","bao","bei","ben","beng","bi","bian","biao", "bie","bin","bing","bo","bu","ca","cai","can","cang","cao","ce","ceng","cha","chai","chan","chang","chao","che","chen", "cheng","chi","chong","chou","chu","chuai","chuan","chuang","chui","chun","chuo","ci","cong","cou","cu","cuan","cui", "cun","cuo","da","dai","dan","dang","dao","de","deng","di","dian","diao","die","ding","diu","dong","dou","du","duan", "dui","dun","duo","e","en","er","fa","fan","fang","fei","fen","feng","fo","fou","fu","ga","gai","gan","gang","gao", "ge","gei","gen","geng","gong","gou","gu","gua","guai","guan","guang","gui","gun","guo","ha","hai","han","hang", "hao","he","hei","hen","heng","hong","hou","hu","hua","huai","huan","huang","hui","hun","huo","ji","jia","jian", "jiang","jiao","jie","jin","jing","jiong","jiu","ju","juan","jue","jun","ka","kai","kan","kang","kao","ke","ken", "keng","kong","kou","ku","kua","kuai","kuan","kuang","kui","kun","kuo","la","lai","lan","lang","lao","le","lei", "leng","li","lia","lian","liang","liao","lie","lin","ling","liu","long","lou","lu","lv","luan","lue","lun","luo", "ma","mai","man","mang","mao","me","mei","men","meng","mi","mian","miao","mie","min","ming","miu","mo","mou","mu", "na","nai","nan","nang","nao","ne","nei","nen","neng","ni","nian","niang","niao","nie","nin","ning","niu","nong", "nu","nv","nuan","nue","nuo","o","ou","pa","pai","pan","pang","pao","pei","pen","peng","pi","pian","piao","pie", "pin","ping","po","pu","qi","qia","qian","qiang","qiao","qie","qin","qing","qiong","qiu","qu","quan","que","qun", "ran","rang","rao","re","ren","reng","ri","rong","rou","ru","ruan","rui","run","ruo","sa","sai","san","sang", "sao","se","sen","seng","sha","shai","shan","shang","shao","she","shen","sheng","shi","shou","shu","shua", "shuai","shuan","shuang","shui","shun","shuo","si","song","sou","su","suan","sui","sun","suo","ta","tai", "tan","tang","tao","te","teng","ti","tian","tiao","tie","ting","tong","tou","tu","tuan","tui","tun","tuo", "wa","wai","wan","wang","wei","wen","weng","wo","wu","xi","xia","xian","xiang","xiao","xie","xin","xing", "xiong","xiu","xu","xuan","xue","xun","ya","yan","yang","yao","ye","yi","yin","ying","yo","yong","you", "yu","yuan","yue","yun","za","zai","zan","zang","zao","ze","zei","zen","zeng","zha","zhai","zhan","zhang", "zhao","zhe","zhen","zheng","zhi","zhong","zhou","zhu","zhua","zhuai","zhuan","zhuang","zhui","zhun","zhuo", "zi","zong","zou","zu","zuan","zui","zun","zuo"}; /// <summary> /// 获取拼音 /// </summary> /// <param name="str">汉字</param> /// <returns></returns> public static string Convert(string str) { byte[] array = new byte[2]; string returnstr = ""; int chrasc = 0; int i1 = 0; int i2 = 0; char[] nowchar = str.ToCharArray(); for (int j = 0; j < nowchar.Length; j++) { byte[] btchk = System.Text.Encoding.Default.GetBytes(nowchar[j].ToString()); if (btchk.Length == 1) { returnstr += nowchar[j].ToString(); continue; } array = btchk; //array = System.Text.Encoding.Default.GetBytes(nowchar[j].ToString()); i1 = (short)(array[0]); i2 = (short)(array[1]); chrasc = i1 * 256 + i2 - 65536; if (chrasc > 0 && chrasc < 160) { returnstr += nowchar[j]; } else { for (int i = (pyvalue.Length - 1); i >= 0; i--) { if (pyvalue[i] <= chrasc) { returnstr += pystr[i]; break; } } } } return returnstr; } /// <summary> /// 获取拼音首字母 /// </summary> /// <param name="str">汉字</param> /// <returns></returns> public static string GetShortPY(string str) { string tempStr = ""; foreach (char c in str) { if ((int)c >= 33 && (int)c <= 126) { tempStr += c.ToString(); //字母和符号原样保留 } else { if ((int)c != 32)//如果不是空格,那么转换 { tempStr += GetPYChar(c.ToString()); //累加拼音声母 } else//如果是空格那么在字符串中间+上一个空字符 { tempStr += " "; } } } return tempStr; } private static string GetPYChar(string c) { byte[] array = new byte[2]; array = System.Text.Encoding.Default.GetBytes(c); int i = (short)(array[0] - ‘\0‘) * 256 + ((short)(array[1] - ‘\0‘)); if (i < 0xB0A1) return ""; if (i < 0xB0C5) return "a"; if (i < 0xB2C1) return "b"; if (i < 0xB4EE) return "c"; if (i < 0xB6EA) return "d"; if (i < 0xB7A2) return "e"; if (i < 0xB8C1) return "f"; if (i < 0xB9FE) return "g"; if (i < 0xBBF7) return "h"; if (i < 0xBFA6) return "j"; if (i < 0xC0AC) return "k"; if (i < 0xC2E8) return "l"; if (i < 0xC4C3) return "m"; if (i < 0xC5B6) return "n"; if (i < 0xC5BE) return "o"; if (i < 0xC6DA) return "p"; if (i < 0xC8BB) return "q"; if (i < 0xC8F6) return "r"; if (i < 0xCBFA) return "s"; if (i < 0xCDDA) return "t"; if (i < 0xCEF4) return "w"; if (i < 0xD1B9) return "x"; if (i < 0xD4D1) return "y"; if (i < 0xD7FA) return "z"; return ""; }}
⑧INI文件读写类 ,新建类INIFile ,全部代码如下:
/// <summary> /// INI文件读写类。 /// Copyright (C) Maticsoft /// </summary> public class INIFile { public string path; public INIFile(string INIPath) { path = INIPath; } [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section,string key,string val,string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section,string key,string def, StringBuilder retVal,int size,string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath); /// <summary> /// 写INI文件 /// </summary> /// <param name="Section"></param> /// <param name="Key"></param> /// <param name="Value"></param> public void IniWriteValue(string Section,string Key,string Value) { WritePrivateProfileString(Section,Key,Value,this.path); } /// <summary> /// 读取INI文件 /// </summary> /// <param name="Section"></param> /// <param name="Key"></param> /// <returns></returns> public string IniReadValue(string Section,string Key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section,Key,"",temp, 255, this.path); return temp.ToString(); } public byte[] IniReadValues(string section, string key) { byte[] temp = new byte[255]; int i = GetPrivateProfileString(section, key, "", temp, 255, this.path); return temp; } /// <summary> /// 删除ini文件下所有段落 /// </summary> public void ClearAllSection() { IniWriteValue(null,null,null); } /// <summary> /// 删除ini文件下personal段落下的所有键 /// </summary> /// <param name="Section"></param> public void ClearSection(string Section) { IniWriteValue(Section,null,null); } }
⑨页面数据效验类,可以新建类 PageValidate,全部代码如下:
/// <summary> /// 页面数据校验类 /// Copyright (C) Maticsoft 2004-2011 /// </summary> public class PageValidate { private static Regex RegPhone = new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$"); private static Regex RegNumber = new Regex("^[0-9]+$"); private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$"); private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$"); private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$ private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样 private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]"); public PageValidate() { } #region 数字字符串检查 public static bool IsPhone(string inputData) { Match m = RegPhone.Match(inputData); return m.Success; } /// <summary> /// 检查Request查询字符串的键值,是否是数字,最大长度限制 /// </summary> /// <param name="req">Request</param> /// <param name="inputKey">Request的键值</param> /// <param name="maxLen">最大长度</param> /// <returns>返回Request查询字符串</returns> public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen) { string retVal = string.Empty; if(inputKey != null && inputKey != string.Empty) { retVal = req.QueryString[inputKey]; if(null == retVal) retVal = req.Form[inputKey]; if(null != retVal) { retVal = SqlText(retVal, maxLen); if(!IsNumber(retVal)) retVal = string.Empty; } } if(retVal == null) retVal = string.Empty; return retVal; } /// <summary> /// 是否数字字符串 /// </summary> /// <param name="inputData">输入字符串</param> /// <returns></returns> public static bool IsNumber(string inputData) { Match m = RegNumber.Match(inputData); return m.Success; } /// <summary> /// 是否数字字符串 可带正负号 /// </summary> /// <param name="inputData">输入字符串</param> /// <returns></returns> public static bool IsNumberSign(string inputData) { Match m = RegNumberSign.Match(inputData); return m.Success; } /// <summary> /// 是否是浮点数 /// </summary> /// <param name="inputData">输入字符串</param> /// <returns></returns> public static bool IsDecimal(string inputData) { Match m = RegDecimal.Match(inputData); return m.Success; } /// <summary> /// 是否是浮点数 可带正负号 /// </summary> /// <param name="inputData">输入字符串</param> /// <returns></returns> public static bool IsDecimalSign(string inputData) { Match m = RegDecimalSign.Match(inputData); return m.Success; } #endregion #region 中文检测 /// <summary> /// 检测是否有中文字符 /// </summary> /// <param name="inputData"></param> /// <returns></returns> public static bool IsHasCHZN(string inputData) { Match m = RegCHZN.Match(inputData); return m.Success; } #endregion #region 邮件地址 /// <summary> /// 是否是浮点数 可带正负号 /// </summary> /// <param name="inputData">输入字符串</param> /// <returns></returns> public static bool IsEmail(string inputData) { Match m = RegEmail.Match(inputData); return m.Success; } #endregion #region 日期格式判断 /// <summary> /// 日期格式字符串判断 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsDateTime(string str) { try { if (!string.IsNullOrEmpty(str)) { DateTime.Parse(str); return true; } else { return false; } } catch { return false; } } #endregion #region 其他 /// <summary> /// 检查字符串最大长度,返回指定长度的串 /// </summary> /// <param name="sqlInput">输入字符串</param> /// <param name="maxLength">最大长度</param> /// <returns></returns> public static string SqlText(string sqlInput, int maxLength) { if(sqlInput != null && sqlInput != string.Empty) { sqlInput = sqlInput.Trim(); if(sqlInput.Length > maxLength)//按最大长度截取字符串 sqlInput = sqlInput.Substring(0, maxLength); } return sqlInput; } /// <summary> /// 字符串编码 /// </summary> /// <param name="inputData"></param> /// <returns></returns> public static string HtmlEncode(string inputData) { return HttpUtility.HtmlEncode(inputData); } /// <summary> /// 设置Label显示Encode的字符串 /// </summary> /// <param name="lbl"></param> /// <param name="txtInput"></param> public static void SetLabel(Label lbl, string txtInput) { lbl.Text = HtmlEncode(txtInput); } public static void SetLabel(Label lbl, object inputObj) { SetLabel(lbl, inputObj.ToString()); } //字符串清理 public static string InputText(string inputString, int maxLength) { StringBuilder retVal = new StringBuilder(); // 检查是否为空 if ((inputString != null) && (inputString != String.Empty)) { inputString = inputString.Trim(); //检查长度 if (inputString.Length > maxLength) inputString = inputString.Substring(0, maxLength); //替换危险字符 for (int i = 0; i < inputString.Length; i++) { switch (inputString[i]) { case ‘"‘: retVal.Append("""); break; case ‘<‘: retVal.Append("<"); break; case ‘>‘: retVal.Append(">"); break; default: retVal.Append(inputString[i]); break; } } retVal.Replace("‘", " ");// 替换单引号 } return retVal.ToString(); } /// <summary> /// 转换成 HTML code /// </summary> /// <param name="str">string</param> /// <returns>string</returns> public static string Encode(string str) { str = str.Replace("&","&"); str = str.Replace("‘","‘‘"); str = str.Replace("\"","""); str = str.Replace(" "," "); str = str.Replace("<","<"); str = str.Replace(">",">"); str = str.Replace("\n","<br>"); return str; } /// <summary> ///解析html成 普通文本 /// </summary> /// <param name="str">string</param> /// <returns>string</returns> public static string Decode(string str) { str = str.Replace("<br>","\n"); str = str.Replace(">",">"); str = str.Replace("<","<"); str = str.Replace(" "," "); str = str.Replace(""","\""); return str; } public static string SqlTextClear(string sqlText) { if (sqlText == null) { return null; } if (sqlText == "") { return ""; } sqlText = sqlText.Replace(",", "");//去除, sqlText = sqlText.Replace("<", "");//去除< sqlText = sqlText.Replace(">", "");//去除> sqlText = sqlText.Replace("--", "");//去除-- sqlText = sqlText.Replace("‘", "");//去除‘ sqlText = sqlText.Replace("\"", "");//去除" sqlText = sqlText.Replace("=", "");//去除= sqlText = sqlText.Replace("%", "");//去除% sqlText = sqlText.Replace(" ", "");//去除空格 return sqlText; } #endregion #region 是否由特定字符组成 public static bool isContainSameChar(string strInput) { string charInput = string.Empty; if (!string.IsNullOrEmpty(strInput)) { charInput = strInput.Substring(0, 1); } return isContainSameChar(strInput, charInput, strInput.Length); } public static bool isContainSameChar(string strInput, string charInput, int lenInput) { if (string.IsNullOrEmpty(charInput)) { return false; } else { Regex RegNumber = new Regex(string.Format("^([{0}])+$", charInput)); //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput)); Match m = RegNumber.Match(strInput); return m.Success; } } #endregion #region 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查 /// <summary> /// 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查 /// </summary> public static bool isContainSpecChar(string strInput) { string[] list = new string[] { "123456", "654321" }; bool result = new bool(); for (int i = 0; i < list.Length; i++) { if (strInput == list[i]) { result = true; break; } } return result; } #endregion }
⑩处理枚举类,新建类RenumDropList,全部代码如下:
/// <summary> /// 处理枚举类 /// </summary> public class RenumDropList { /// <summary> /// 讲枚举绑定在DropDownList上 /// </summary> /// <param name="list">类型</param> /// <param name="text">第一项文字</param> /// <param name="TypeEnum">枚举(默认第一项为0)</param> public static void BindDropDownList(DropDownList list,string text,Type TypeEnum) { List<ListItem> TypeList = new List<ListItem>(); // TypeList.Add(new ListItem(text, value)); TypeList.Add(new ListItem { Text = ""+text+"", Value = http://www.mamicode.com/"0"}); foreach (object type in Enum.GetValues(TypeEnum)) { TypeList.Add(new ListItem(type.ToString(), ((int)type).ToString())); } list.DataSource = TypeList; list.DataTextField = "text"; list.DataValueField = "value"; list.DataBind(); } /// <summary> /// 讲枚举绑定在DropDownList上 /// </summary> /// <param name="list">控件</param> /// <param name="TypeEnum">枚举</param> public static void BindDropDownList(DropDownList list, Type TypeEnum) { List<ListItem> TypeList = new List<ListItem>(); foreach (object type in Enum.GetValues(TypeEnum)) { TypeList.Add(new ListItem(type.ToString(), ((int)type).ToString())); } list.DataSource = TypeList; list.DataTextField = "text"; list.DataValueField = "value"; list.DataBind(); } /// <summary> /// 讲枚举绑定在RadioButtonList上面 /// </summary> /// <param name="list"></param> public static void BindRadioButtonList(RadioButtonList list,Type TypeEnem) { List<ListItem> TypeList = new List<ListItem>(); foreach (object type in Enum.GetValues(TypeEnem)) { string str=type.ToString(); if (str.Contains(‘X‘)) { str = str.Replace("X", "/"); } TypeList.Add(new ListItem(str, ((int)type).ToString())); } list.DataSource = TypeList; list.DataTextField = "text"; list.DataValueField = "value"; list.DataBind(); } /// <summary> /// 讲枚举绑定在DropDownList上 /// </summary> /// <param name="list">类型</param> /// <param name="text">第一项文字</param> /// <param name="TypeEnum">枚举(默认第一项为0)</param> public static void BindDropDownList_Replace(DropDownList list, Type TypeEnum) { List<ListItem> TypeList = new List<ListItem>(); // TypeList.Add(new ListItem(text, value)); //TypeList.Add(new ListItem { Text = "" + text + "", Value = "http://www.mamicode.com/0" }); foreach (object type in Enum.GetValues(TypeEnum)) { string str=type.ToString(); if (str.Contains(‘N‘) || str.Contains(‘D‘) || str.Contains(‘G‘)||str.Contains(‘M‘)||str.Contains(‘Q‘)) { str=str.Replace("N", "$"); str=str.Replace("D", ","); str=str.Replace("G", " - "); str = str.Replace("M", "."); str = str.Replace("Q", ""); } TypeList.Add(new ListItem(str, ((int)type).ToString())); } list.DataSource = TypeList; list.DataTextField = "text"; list.DataValueField = "value"; list.DataBind(); } /// <summary> /// 选中某一项 /// </summary> /// <param name="radio">类型</param> /// <param name="value">值</param> public static void RadioButtonChecked(RadioButtonList radio,string value) { for (int i = 0; i < radio.Items.Count; i++) { if (radio.Items[i].Value != value) { radio.Items[i].Selected = false; // continue; } else { radio.ClearSelection(); radio.Items[i].Selected = true; } } } /// <summary> /// 选中某一项 /// </summary> /// <param name="radio">类型</param> /// <param name="value">值</param> public static void DropDownListChecked(DropDownList drop, string value) { for (int i = 0; i <drop.Items.Count; i++) { if (drop.Items[i].Value != value) { drop.Items[i].Selected = false; //continue; } else { drop.ClearSelection(); drop.Items[i].Selected = true; } } } /// <summary> /// 选中某一项 /// </summary> /// <param name="radio">类型</param> /// <param name="value">值</param> public static void DropListChecked(DropDownList drop, string text) { // drop.ClearSelection(); for (int i = 0; i < drop.Items.Count; i++) { if (drop.Items[i].Text != text) { drop.Items[i].Selected = false; //continue; } else { drop.ClearSelection(); drop.Items[i].Selected = true; } } } /// <summary> /// 绑定枚举在CheckBoxList上 /// </summary> /// <param name="list"></param> /// <param name="TypeEnum"></param> public static void BindCheckBoxList(CheckBoxList list, Type TypeEnum) { List<ListItem> TypeList = new List<ListItem>(); foreach (object type in Enum.GetValues(TypeEnum)) { TypeList.Add(new ListItem(type.ToString(), ((int)type).ToString())); } list.DataSource = TypeList; list.DataTextField = "text"; list.DataValueField = "value"; list.DataBind(); } }
11 转换人民币大小金额 ,新建类Rmb ,全部代码如下:
/// <summary> /// Rmb 的摘要说明。 /// </summary> public class Rmb { /// <summary> /// 转换人民币大小金额 /// </summary> /// <param name="num">金额</param> /// <returns>返回大写形式</returns> public static string CmycurD(decimal num) { string str1 = "零壹贰叁肆伍陆柒捌玖"; //0-9所对应的汉字 string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字 string str3 = ""; //从原num值中取出的值 string str4 = ""; //数字的字符串形式 string str5 = ""; //人民币大写金额形式 int i; //循环变量 int j; //num的值乘以100的字符串长度 string ch1 = ""; //数字的汉语读法 string ch2 = ""; //数字位的汉字读法 int nzero = 0; //用来计算连续的零值是几个 int temp; //从原num值中取出的值 num = Math.Round(Math.Abs(num), 2); //将num取绝对值并四舍五入取2位小数 str4 = ((long)(num * 100)).ToString(); //将num乘100并转换成字符串形式 j = str4.Length; //找出最高位 if (j > 15) { return "溢出"; } str2 = str2.Substring(15 - j); //取出对应位数的str2的值。如:200.55,j为5所以str2=佰拾元角分 //循环取出每一位需要转换的值 for (i = 0; i < j; i++) { str3 = str4.Substring(i, 1); //取出需转换的某一位的值 temp = Convert.ToInt32(str3); //转换为数字 if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15)) { //当所取位数不为元、万、亿、万亿上的数字时 if (str3 == "0") { ch1 = ""; ch2 = ""; nzero = nzero + 1; } else { if (str3 != "0" && nzero != 0) { ch1 = "零" + str1.Substring(temp * 1, 1); ch2 = str2.Substring(i, 1); nzero = 0; } else { ch1 = str1.Substring(temp * 1, 1); ch2 = str2.Substring(i, 1); nzero = 0; } } } else { //该位是万亿,亿,万,元位等关键位 if (str3 != "0" && nzero != 0) { ch1 = "零" + str1.Substring(temp * 1, 1); ch2 = str2.Substring(i, 1); nzero = 0; } else { if (str3 != "0" && nzero == 0) { ch1 = str1.Substring(temp * 1, 1); ch2 = str2.Substring(i, 1); nzero = 0; } else { if (str3 == "0" && nzero >= 3) { ch1 = ""; ch2 = ""; nzero = nzero + 1; } else { if (j >= 11) { ch1 = ""; nzero = nzero + 1; } else { ch1 = ""; ch2 = str2.Substring(i, 1); nzero = nzero + 1; } } } } } if (i == (j - 11) || i == (j - 3)) { //如果该位是亿位或元位,则必须写上 ch2 = str2.Substring(i, 1); } str5 = str5 + ch1 + ch2; if (i == j - 1 && str3 == "0") { //最后一位(分)为0时,加上“整” str5 = str5 + ‘整‘; } } if (num == 0) { str5 = "零元整"; } return str5; } /**/ /// <summary> /// 一个重载,将字符串先转换成数字在调用CmycurD(decimal num) /// </summary> /// <param name="num">用户输入的金额,字符串形式未转成decimal</param> /// <returns></returns> public static string CmycurD(string numstr) { try { decimal num = Convert.ToDecimal(numstr); return CmycurD(num); } catch { return "非数字形式!"; } } }
12 时间帮助类 TimeParser,全部代码如下:
public class TimeParser { /// <summary> /// 把秒转换成分钟 /// </summary> /// <returns></returns> public static int SecondToMinute(int Second) { decimal mm = (decimal)((decimal)Second / (decimal)60); return Convert.ToInt32(Math.Ceiling(mm)); } #region 返回某年某月最后一天 /// <summary> /// 返回某年某月最后一天 /// </summary> /// <param name="year">年份</param> /// <param name="month">月份</param> /// <returns>日</returns> public static int GetMonthLastDate(int year, int month) { DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month)); int Day = lastDay.Day; return Day; } #endregion #region 返回时间差 public static string DateDiff(DateTime DateTime1, DateTime DateTime2) { string dateDiff = null; try { //TimeSpan ts1 = new TimeSpan(DateTime1.Ticks); //TimeSpan ts2 = new TimeSpan(DateTime2.Ticks); //TimeSpan ts = ts1.Subtract(ts2).Duration(); TimeSpan ts = DateTime2 - DateTime1; if (ts.Days >=1) { dateDiff = DateTime1.Month.ToString() + "月" + DateTime1.Day.ToString() + "日"; } else { if (ts.Hours > 1) { dateDiff = ts.Hours.ToString() + "小时前"; } else { dateDiff = ts.Minutes.ToString() + "分钟前"; } } } catch { } return dateDiff; } #endregion }
13 URL的操作类,全部代码如下:
/// <summary> /// URL的操作类 /// </summary> public class UrlOper { static System.Text.Encoding encoding = System.Text.Encoding.UTF8; #region URL的64位编码 public static string Base64Encrypt(string sourthUrl) { string eurl = HttpUtility.UrlEncode(sourthUrl); eurl = Convert.ToBase64String(encoding.GetBytes(eurl)); return eurl; } #endregion #region URL的64位解码 public static string Base64Decrypt(string eStr) { if (!IsBase64(eStr)) { return eStr; } byte[] buffer = Convert.FromBase64String(eStr); string sourthUrl = encoding.GetString(buffer); sourthUrl = HttpUtility.UrlDecode(sourthUrl); return sourthUrl; } /// <summary> /// 是否是Base64字符串 /// </summary> /// <param name="eStr"></param> /// <returns></returns> public static bool IsBase64(string eStr) { if ((eStr.Length % 4) != 0) { return false; } if (!Regex.IsMatch(eStr, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase)) { return false; } return true; } #endregion /// <summary> /// 添加URL参数 /// </summary> public static string AddParam(string url, string paramName, string value) { Uri uri = new Uri(url); if (string.IsNullOrEmpty(uri.Query)) { string eval = HttpContext.Current.Server.UrlEncode(value); return String.Concat(url, "?" + paramName + "=" + eval); } else { string eval = HttpContext.Current.Server.UrlEncode(value); return String.Concat(url, "&" + paramName + "=" + eval); } } /// <summary> /// 更新URL参数 /// </summary> public static string UpdateParam(string url, string paramName, string value) { string keyWord = paramName+"="; int index = url.IndexOf(keyWord)+keyWord.Length; int index1 = url.IndexOf("&", index); if (index1 == -1) { url = url.Remove(index, url.Length - index); url = string.Concat(url, value); return url; } url = url.Remove(index,index1 - index); url = url.Insert(index, value); return url; } #region 分析URL所属的域 public static void GetDomain(string fromUrl, out string domain, out string subDomain) { domain = ""; subDomain = ""; try { if (fromUrl.IndexOf("的名片") > -1) { subDomain = fromUrl; domain = "名片"; return; } UriBuilder builder = new UriBuilder(fromUrl); fromUrl = builder.ToString(); Uri u = new Uri(fromUrl); if (u.IsWellFormedOriginalString()) { if (u.IsFile) { subDomain = domain = "客户端本地文件路径"; } else { string Authority = u.Authority; string[] ss = u.Authority.Split(‘.‘); if (ss.Length == 2) { Authority = "www." + Authority; } int index = Authority.IndexOf(‘.‘, 0); domain = Authority.Substring(index + 1, Authority.Length - index - 1).Replace("comhttp","com"); subDomain = Authority.Replace("comhttp", "com"); if (ss.Length < 2) { domain = "不明路径"; subDomain = "不明路径"; } } } else { if (u.IsFile) { subDomain = domain = "客户端本地文件路径"; } else { subDomain = domain = "不明路径"; } } } catch { subDomain = domain = "不明路径"; } } /// <summary> /// 分析 url 字符串中的参数信息 /// </summary> /// <param name="url">输入的 URL</param> /// <param name="baseUrl">输出 URL 的基础部分</param> /// <param name="nvc">输出分析后得到的 (参数名,参数值) 的集合</param> public static void ParseUrl(string url, out string baseUrl, out NameValueCollection nvc) { if (url == null) throw new ArgumentNullException("url"); nvc = new NameValueCollection(); baseUrl = ""; if (url == "") return; int questionMarkIndex = url.IndexOf(‘?‘); if (questionMarkIndex == -1) { baseUrl = url; return; } baseUrl = url.Substring(0, questionMarkIndex); if (questionMarkIndex == url.Length - 1) return; string ps = url.Substring(questionMarkIndex + 1); // 开始分析参数对 Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled); MatchCollection mc = re.Matches(ps); foreach (Match m in mc) { nvc.Add(m.Result("$2").ToLower(), m.Result("$3")); } } #endregion }
14 SessionHelper,全部代码如下:
public class SessionHelper { public const string LOGININFO_NAME = "LOGININFO_NAME"; public static T Get<T>(string name) { var value =http://www.mamicode.com/ HttpContext.Current.Session[name]; if (value =http://www.mamicode.com/= null) { return default(T); } else { return (T)value; } } public static void Set(string name, object value) { var s = HttpContext.Current.Session[name]; if (s != null) { HttpContext.Current.Session[name] = value; } else { HttpContext.Current.Session.Add(name, value); } } public static void Delete(string name) { HttpContext.Current.Session.Remove(name); } public static void Clear() { HttpContext.Current.Session.Clear(); } public static object GetLoginInfo() { var value =http://www.mamicode.com/ HttpContext.Current.Session[LOGININFO_NAME]; return value; } public static void SetLoginInfo(object value) { var s = HttpContext.Current.Session[LOGININFO_NAME]; if (s != null) { HttpContext.Current.Session[LOGININFO_NAME] = value; } else { HttpContext.Current.Session.Add(LOGININFO_NAME, value); } } public static void RemoveLoginInfo() { HttpContext.Current.Session.Remove(LOGININFO_NAME); } }
使用方式:
例如,登陆模块,用户点击登录之后可设置:
SessionHelper.SetLoginInfo(用户实体);
Session使用:
if (SessionHelper.GetLoginInfo() != null) { 实例化用户实体= (实体)SessionHelper.GetLoginInfo(); }
用户退出最好清空Session
SessionHelper.RemoveLoginInfo();
15 验证码帮助类
效果:
新建验证码帮助类VerificationCodeHelper,全部代码如下:
public class VerificationCodeHelper { private static Color BackColor = Color.White; private static int Width = 62; private static int Height = 21; private Random _random; // private string _code; private int _brushNameIndex; public byte[] GetVCode(string codeStr) { _random = new Random(); using (Bitmap img = new Bitmap(Width, Height)) { // _code = GetRandomCode(); // System.Web.HttpContext.Current.Session["vcode"] = _code; using (Graphics g = Graphics.FromImage(img)) { g.Clear(Color.White);//绘画背景颜色 Paint_Text(g, codeStr);// 绘画文字 // g.DrawString(strCode, new Font("微软雅黑", 15), Brushes.Blue, new PointF(5, 2));// 绘画文字 Paint_TextStain(img);// 绘画噪音点 g.DrawRectangle(Pens.DarkGray, 0, 0, Width - 1, Height - 1);//绘画边框 using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { //将图片 保存到内存流中 img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //将内存流 里的 数据 转成 byte 数组 返回 return ms.ToArray(); } } } } /// <summary> /// 绘画文字 /// </summary> /// <param name="g"></param> private void Paint_Text(Graphics g, string code) { g.DrawString(code, GetFont(), GetBrush(), 3, 1); } /// <summary> /// 绘画文字噪音点 /// </summary> /// <param name="g"></param> private void Paint_TextStain(Bitmap b) { string[] BrushName = new string[] { "OliveDrab", "ForestGreen", "DarkCyan", "LightSlateGray", "RoyalBlue", "SlateBlue", "DarkViolet", "MediumVioletRed", "IndianRed", "Firebrick", "Chocolate", "Peru", "Goldenrod" }; for (int n = 0; n < 30; n++) { int x = _random.Next(Width); int y = _random.Next(Height); b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex])); } } /// <summary> /// 随机取一个字体 /// </summary> /// <returns></returns> private Font GetFont() { string[] FontItems = new string[]{ "Arial", "Helvetica", "Geneva", "sans-serif", "Verdana" }; int fontIndex = _random.Next(0, FontItems.Length); FontStyle fontStyle = GetFontStyle(_random.Next(0, 2)); return new Font(FontItems[fontIndex], 12, fontStyle); } /**/ /**/ /**/ /// <summary> /// 随机取一个笔刷 /// </summary> /// <returns></returns> private Brush GetBrush() { Brush[] BrushItems = new Brush[]{ Brushes.OliveDrab, Brushes.ForestGreen, Brushes.DarkCyan, Brushes.LightSlateGray, Brushes.RoyalBlue, Brushes.SlateBlue, Brushes.DarkViolet, Brushes.MediumVioletRed, Brushes.IndianRed, Brushes.Firebrick, Brushes.Chocolate, Brushes.Peru, Brushes.Goldenrod }; int brushIndex = _random.Next(0, BrushItems.Length); _brushNameIndex = brushIndex; return BrushItems[brushIndex]; } /// <summary> /// 绘画背景颜色 /// </summary> /// <param name="g"></param> private void Paint_Background(Graphics g) { g.Clear(BackColor); } /**/ /**/ /**/ /// <summary> /// 取一个字体的样式 /// </summary> /// <param name="index"></param> /// <returns></returns> private FontStyle GetFontStyle(int index) { switch (index) { case 0: return FontStyle.Bold; case 1: return FontStyle.Italic; default: return FontStyle.Regular; } } /// <summary> /// 取得一个 4 位的随机码 /// </summary> /// <returns></returns> public string GetRandomCode() { return Guid.NewGuid().ToString().Substring(0, 5); } }
使用:
前台HTML
<img id="checkloing" src=http://www.mamicode.com/"/Login/VCode" class="loginFormCheckCodeImg" onclick="reloadcode(‘/Login/VCode‘)" title="Can not see clearly, change one." />
JS:
//刷新验证码 function reloadcode(srcStr) { document.getElementById("checkloing").src = http://www.mamicode.com/srcStr + "?rand=" + Math.random(); }
Controller
/// <summary> /// 生成验证码 /// </summary> /// <returns></returns> [OutputCache(Duration = 10, VaryByParam = "rand")]//缓存10秒钟 [AllowAnonymous]//跳过登陆验证 public ActionResult VCode() { VerificationCodeHelper vcode = new VerificationCodeHelper(); string codeStr = vcode.GetRandomCode(); if (!string.IsNullOrEmpty(codeStr)) { byte[] arrImg = vcode.GetVCode(codeStr); Session["code"] = codeStr; return File(arrImg, "image/gif"); } else { return RedirectToAction("/控制器/VCode?rand=" + Guid.NewGuid().ToString().Substring(1, 10), "image/jpeg"); } }
16 CookieHelper帮助类
using System;using System.Web;namespace ConsoleApplication5{ /// <summary> /// Cookie 助手 /// </summary> public sealed class CookieHelper { /// <summary> /// 添加一个 Cookie /// </summary> /// <param name="name">名</param> /// <param name="value">值</param> public static void Add(string name, string value) { var cookie = new HttpCookie(name, value); HttpContext.Current.Response.Cookies.Add(cookie); } /// <summary> /// 添加一个 Cookie /// </summary> /// <param name="name">名</param> /// <param name="value">值</param> /// <param name="expires">过期日期和时间</param> public static void Add(string name, string value, DateTime expires) { var cookie = new HttpCookie(name, value) { Expires = expires }; HttpContext.Current.Response.Cookies.Add(cookie); } /// <summary> /// 获取 Cookie 值 /// </summary> /// <param name="name">名</param> /// <returns></returns> public static string Get(string name) { var cookie = HttpContext.Current.Request.Cookies[name]; return cookie == null ? string.Empty : cookie.Value; } }}
17 JsonHepler
using System;using System.Collections.Generic;using System.Web;using System.Text;using System.Reflection;using System.Collections;using System.Data;using System.Data.Common;using System.Web.Script.Serialization;/// <summary>///JsonHandleHelper 的摘要说明/// </summary>public class JsonHandleHelper{ /// <summary> /// 对象转JSON /// </summary> /// <param name="obj">对象</param> /// <returns>JSON格式的字符串</returns> public static string ObjectToJSON(object obj) { JavaScriptSerializer jss =new JavaScriptSerializer(); try { return jss.Serialize(obj); } catch(Exception ex) { throw new Exception("JSONHelper.ObjectToJSON(): "+ ex.Message); } } /// <summary> /// 转换对象为JSON格式数据 /// </summary> /// <typeparam name="T">类</typeparam> /// <param name="obj">对象</param> /// <returns>字符格式的JSON数据</returns> public static string GetJSON<T>(object obj) { string result = String.Empty; try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { serializer.WriteObject(ms, obj); result = System.Text.Encoding.UTF8.GetString(ms.ToArray()); } } catch (Exception ex) { throw ex; } return result; } /// <summary> /// 转换List<T>的数据为JSON格式 /// </summary> /// <typeparam name="T">类</typeparam> /// <param name="vals">列表值</param> /// <returns>JSON格式数据</returns> public static string JSON<T>(List<T> vals) { System.Text.StringBuilder st = new System.Text.StringBuilder(); try { System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); foreach (T city in vals) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { s.WriteObject(ms, city); st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray())); } } } catch (Exception ex) { throw ex; } return st.ToString(); } /// <summary> /// JSON格式字符转换为T类型的对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonStr"></param> /// <returns></returns> public static T ParseFormByJson<T>(string jsonStr) { T obj = Activator.CreateInstance<T>(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } } /// <summary> /// 数据表转键值对集合 /// 把DataTable转成 List集合, 存每一行 /// 集合中放的是键值对字典,存每一列 /// </summary> /// <param name="dt">数据表</param> /// <returns>哈希表数组</returns> public static List<Dictionary<string, object>> DataTableToList(DataTable dt) { List<Dictionary<string, object>> list= new List<Dictionary<string, object>>(); foreach (DataRow dr in dt.Rows) { Dictionary<string, object> dic = new Dictionary<string, object>(); foreach (DataColumn dc in dt.Columns) { dic.Add(dc.ColumnName, dr[dc.ColumnName]); } list.Add(dic); } return list; } /// <summary> /// 数据集转键值对数组字典 /// </summary> /// <param name="dataSet">数据集</param> /// <returns>键值对数组字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds) { Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>(); foreach (DataTable dt in ds.Tables) result.Add(dt.TableName, DataTableToList(dt)); return result; } /// <summary> /// 数据表转JSON /// </summary> /// <param name="dataTable">数据表</param> /// <returns>JSON字符串</returns> public static string DataTableToJSON(DataTable dt) { return ObjectToJSON(DataTableToList(dt)); } /// <summary> /// JSON文本转对象,泛型方法 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="jsonText">JSON文本</param> /// <returns>指定类型的对象</returns> public static T JSONToObject<T>(string jsonText) { JavaScriptSerializer jss =new JavaScriptSerializer(); try { return jss.Deserialize<T>(jsonText); } catch(Exception ex) { throw new Exception("JSONHelper.JSONToObject(): "+ ex.Message); } } /// <summary> /// 将JSON文本转换为数据表数据 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>数据表字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText) { return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText); } /// <summary> /// 将JSON文本转换成数据行 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>数据行的字典</returns> public static Dictionary<string, object> DataRowFromJSON(string jsonText) { return JSONToObject<Dictionary<string, object>>(jsonText); } }
未完待续,持续更新。。。。
C# 各种帮助类大全