标签:
/// <summary> /// 底层及数据库操作通用类 /// </summary> public class CmdMethods { /// <summary> /// 参数标识符 /// </summary> public static string preParameter = "@"; /// <summary> /// 获取数据库连接 /// </summary>zlf 2015-02-06 /// <param name="useDb">数据库</param> public static string GetConnectionString(string useDb) { string val = String.Empty; switch (useDb) { case "a": val = System.Configuration.ConfigurationManager.ConnectionStrings["activitydb"].ToString(); break; case "c": val = System.Configuration.ConfigurationManager.ConnectionStrings["CommonDb"].ToString(); break; case "d": val = System.Configuration.ConfigurationManager.ConnectionStrings["DonationDb"].ToString(); break; case "p": val = System.Configuration.ConfigurationManager.ConnectionStrings["ProjectsDb"].ToString(); break; case "u": val = System.Configuration.ConfigurationManager.ConnectionStrings["UsersDb"].ToString(); break; case "l": val = System.Configuration.ConfigurationManager.ConnectionStrings["LogDb"].ToString(); break; default: break; } return val; } /// <summary> /// 执行数据库操作 /// </summary>zlf 2015-02-06 /// <param name="useDb">数据库</param> /// <param name="sql">数据库执行语句</param> /// <returns>影响的行数</returns> public static int ExecuteNonQuery(string useDb, string sql) { var connStr = GetConnectionString(useDb); if (String.IsNullOrEmpty(connStr)) return 0; using (SqlConnection con = new SqlConnection(connStr)) { try { con.Open(); SqlCommand cmd = new SqlCommand(sql, con); return cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException e) { con.Close(); throw e; } } } /// <summary> /// 执行数据库操作 /// </summary>zlf 2015-02-06 /// <param name="useDb">数据库</param> /// <param name="sql">数据库执行语句</param> /// <param name="parameters">参数</param> /// <returns>受影响的行数</returns> public static int ExecuteNonQuery(string useDb, string sql, SqlParameter[] parameters) { var connStr = GetConnectionString(useDb); if (String.IsNullOrEmpty(connStr)) return 0; using (SqlConnection con = new SqlConnection(connStr)) { try { con.Open(); SqlCommand cmd = new SqlCommand(sql, con); cmd.Parameters.AddRange(parameters); return cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException e) { con.Close(); throw e; } } } /// <summary> /// 查询单个值 /// </summary>zlf 2015-02-26 /// <param name="useDb">数据库</param> /// <param name="sql">数据库执行语句</param> /// <returns>返回查询所返回的结果集中第一行的第一列或空引用(如果结果集为空).忽略其他列或行</returns> public static object ExecuteScalar(string useDb, string sql) { var connStr = GetConnectionString(useDb); if (String.IsNullOrEmpty(connStr)) return null; using (SqlConnection con = new SqlConnection(connStr)) { try { con.Open(); SqlCommand cmd = new SqlCommand(sql, con); return cmd.ExecuteScalar(); } catch (System.Data.SqlClient.SqlException e) { con.Close(); throw e; } } } /// <summary> /// 执行查询语句,返回DataSet /// </summary>zlf 2015-02-26 /// <param name="useDb">数据库</param> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string useDb, string SQLString) { var connStr = GetConnectionString(useDb); if (String.IsNullOrEmpty(connStr)) return null; using (SqlConnection con = new SqlConnection(connStr)) { DataSet ds = new DataSet(); try { con.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, con); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException e) { con.Close(); throw e; } return ds; } } /// <summary> /// 验证sql匹配条件是否正确(若以and开头则自动去除) /// </summary>zlf 2014-12-10 /// <param name="where">sql匹配条件</param> public static string CheckWhere(string where) { string str = where.TrimStart();//去除前置空格 if (str.ToLower().IndexOf("and ") == 0)//若以and开头则自动去除第一个and { where = str.Substring(4);//若要保留前面一个空格,可以改为3 } //防SQL注入 where = filterSql(where); return where; } /// <summary> /// 过滤SQL语句,防止注入 /// </summary> /// <param name="strSql">Sql语句</param> public static string filterSql(string strSql) { var str = strSql.ToLower().Trim(); str = str.Replace("exec", ""); str = str.Replace("delete", ""); str = str.Replace("master", ""); str = str.Replace("truncate", ""); str = str.Replace("declare", ""); str = str.Replace("create", ""); str = str.Replace("xp_", "no"); return str; } /// <summary> /// 获取指定表中指定列的值 /// </summary>zlf 2015-02-26 /// <param name="useDb">数据库</param> /// <param name="ColumnCode">列编码</param> /// <param name="tbName">数据表名</param> /// <param name="strWhere">匹配条件</param> /// <returns>满足条件的第一行的值</returns> public static string GetColumnValue(string useDb, string ColumnCode, string tbName, string strWhere) { string value = String.Empty; if (String.IsNullOrEmpty(ColumnCode) || String.IsNullOrEmpty(tbName)) { return value; } StringBuilder strSql = new StringBuilder(); strSql.Append("select top 1 " + ColumnCode + " from " + tbName); strWhere = CheckWhere(strWhere); if (!String.IsNullOrEmpty(strWhere)) { if (strWhere.StartsWith("order by")) { strSql.Append(" " + strWhere); } else { strSql.Append(" where " + strWhere); } } try { object obj = ExecuteScalar(useDb, strSql.ToString()); if (obj != null) value = obj.ToString(); } catch //(Exception ex) { } return value; } /// <summary> /// 获取数据集 /// </summary>zlf 2015-02-26 /// <param name="useDb">数据库</param> /// <param name="fileds">列集合</param> /// <param name="tbName">数据表名</param> /// <param name="strWhere">匹配条件</param> /// <returns>满足条件的数据集</returns> public static DataSet GetList(string useDb, string fileds, string tbName, string strWhere) { DataSet ds = null; if (String.IsNullOrEmpty(fileds) || String.IsNullOrEmpty(tbName)) { return ds; } StringBuilder strSql = new StringBuilder(); strSql.Append("select " + fileds + " from " + tbName); strWhere = CheckWhere(strWhere); if (!String.IsNullOrEmpty(strWhere)) { if (strWhere.StartsWith("order by")) { strSql.Append(" " + strWhere); } else { strSql.Append(" where " + strWhere); } } try { ds = Query(useDb, strSql.ToString()); } catch //(Exception ex) { } return ds; } /// <summary> /// 分页获取数据集 /// </summary>zlf 2015-02-26 /// <param name="useDb">数据库 GetDb()</param> /// <param name="fileds">列集合</param> /// <param name="tbName">数据表名</param> /// <param name="strWhere">匹配条件</param> /// <returns>满足条件的数据集</returns> /// <param name="orderby">排序字段 如:addtime desc</param> /// <param name="pageIndex">当前页号</param> /// <param name="pageSize">每页数据量</param> public static DataSet GetListByPage(string useDb, string fileds, string tbName, string strWhere, string orderby, int pageSize, int pageIndex) { DataSet ds = null; if (String.IsNullOrEmpty(fileds) || String.IsNullOrEmpty(tbName) || String.IsNullOrEmpty(orderby)) { return ds; } if (pageSize < 1) pageSize = 10; if (pageIndex < 1) pageIndex = 1; int start = (pageIndex - 1) * pageSize + 1; int end = pageIndex * pageSize; StringBuilder strSql = new StringBuilder(); strSql.Append("select * from ("); strSql.Append("select ROW_NUMBER() OVER (ORDER BY " + orderby + ") as row," + fileds + " from " + tbName); strWhere = CheckWhere(strWhere); if (!String.IsNullOrEmpty(strWhere)) { strSql.Append(" where " + strWhere); } strSql.Append(") as T where T.row between " + start + " and " + end); try { ds = Query(useDb, strSql.ToString()); } catch //(Exception ex) { } return ds; } /// <summary> /// 获取指定表中记录总数 /// </summary>zlf 2015-02-26 /// <param name="useDb">数据库</param> /// <param name="tbName">数据表名</param> /// <param name="strWhere">匹配条件</param> /// <returns>满足条件的记录总数</returns> public static int GetRecordCount(string useDb, string tbName, string strWhere) { int value = 0; if (String.IsNullOrEmpty(tbName)) { return value; } StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) from " + tbName); strWhere = CheckWhere(strWhere); if (!String.IsNullOrEmpty(strWhere)) { strSql.Append(" where " + strWhere); } try { object obj = ExecuteScalar(useDb, strSql.ToString()); if (obj != null) value = Convert.ToInt32(obj); } catch //(Exception ex) { } return value; } /// <summary> /// 更新指定数据库指定表中信息 /// </summary>zlf 2014-12-10 /// <param name="useDb">数据库</param> /// <param name="ColAndVal">列+值(col = ‘val‘,col2=‘val2‘)</param> /// <param name="tbName">数据表名</param> /// <param name="strWhere">匹配条件</param> /// <returns>是否更新成功</returns> public static bool SetValue(string useDb, string ColAndVal, string tbName, string strWhere) { bool value = false; if (String.IsNullOrEmpty(ColAndVal) || String.IsNullOrEmpty(tbName)) { return false; } StringBuilder strSql = new StringBuilder(); strSql.Append("update " + tbName + " set "); strSql.Append(ColAndVal); strWhere = CheckWhere(strWhere); if (!String.IsNullOrEmpty(strWhere)) { strSql.Append(" where " + strWhere); } try { int rows = ExecuteNonQuery(useDb, strSql.ToString()); return rows > 0; } catch //(Exception ex) { } return value; } /// <summary> /// 批量插入记录(不支持html数据) /// </summary>zlf 2015-02-06 /// <param name="useDb">数据库</param> /// <param name="tbName">数据表名</param> /// <param name="fields">字段集合 如:col1,col2,...</param> /// <param name="values">值集合(值中不能包含",") 如:‘val1‘,‘val2‘,...</param> public static bool InsertRecord(string useDb, string tbName, string fields, List<string> values) { bool value = false; if (String.IsNullOrEmpty(tbName) || String.IsNullOrEmpty(fields) || values.Count < 1) { return false; } int colLength = fields.Split(‘,‘).Length; StringBuilder strSql = new StringBuilder(); strSql.Append("insert into " + tbName + "(" + fields + ") "); bool equalLength = false;//字段长度是否与值长度是否相同 for (int i = 0; i < values.Count; i++) { if (values[i].Split(‘,‘).Length == colLength) { equalLength = true; if (i == 0) { strSql.Append(" select " + values[i]); } else { strSql.Append(" union all "); strSql.Append(" select " + values[i]); } } } if (equalLength) { try { int rows = ExecuteNonQuery(useDb, strSql.ToString()); return rows > 0; } catch { } } return value; } /// <summary> /// 添加一条记录(不支持html数据) /// </summary>zlf 2015-02-06 /// <typeparam name="T">实体类 必须保证字段与数据库一致</typeparam> /// <param name="useDb">数据库</param> /// <param name="tbName">数据表名</param> /// <param name="info">数据实体</param> public static bool AddRecord<T>(string useDb, string tbName, T info) where T : class { bool result = false; if (String.IsNullOrEmpty(tbName) || info == null) { return false; } var type = typeof(T); var fields = type.GetProperties(); if (fields.Length < 2) { return false; } StringBuilder sb = new StringBuilder(); sb.Append("insert into " + tbName + "({0}) values ({1})"); var columns = String.Empty; var values = String.Empty; foreach (var p in fields) { var v = p.GetValue(info, null); if (v == null) continue; if (String.IsNullOrEmpty(columns)) { columns += p.Name; values += "‘" + v.ToString().Replace("‘", "") + "‘"; } else { columns += "," + p.Name; values += ",‘" + v.ToString().Replace("‘", "") + "‘"; } } if (!String.IsNullOrEmpty(columns)) { var sql = string.Format(sb.ToString(), columns, values); try { int rows = ExecuteNonQuery(useDb, sql); return rows > 0; } catch { } } return result; } /// <summary> /// 添加一条记录 /// </summary>zlf 2015-02-06 /// <typeparam name="T">实体类 必须保证字段与数据库一致</typeparam> /// <param name="useDb">数据库</param> /// <param name="tbName">数据表名</param> /// <param name="info">数据实体</param> public static bool RecordAdd<T>(string useDb, string tbName, T info) where T : class { if (String.IsNullOrEmpty(tbName) || info == null) { return false; } var type = typeof(T); var fields = type.GetProperties(); if (fields.Length < 2) { return false; } StringBuilder sb = new StringBuilder(); sb.Append("insert into " + tbName + "({0}) values ({1})"); var columns = String.Empty; var values = String.Empty; List<SqlParameter> list = new List<SqlParameter>(); foreach (var p in fields) { var v = p.GetValue(info, null); if (v == null) continue; if (String.IsNullOrEmpty(columns)) { columns += p.Name; values += preParameter + p.Name; } else { columns += "," + p.Name; values += "," + preParameter + p.Name; } list.Add(new SqlParameter(preParameter + p.Name, v)); } if (!String.IsNullOrEmpty(columns)) { var sql = string.Format(sb.ToString(), columns, values); try { int rows = ExecuteNonQuery(useDb, sql, list.ToArray()); return rows > 0; } catch { } } return false; } /// <summary> /// 批量插入记录(逐条) /// </summary>zlf 2015-02-06 /// <typeparam name="T">实体类 必须保证字段与数据库一致</typeparam> /// <param name="useDb">数据库</param> /// <param name="tbName">数据表名</param> /// <param name="list">数据实体集合</param> /// <returns>执行成功的数据数</returns> public static int RecordInsert<T>(string useDb, string tbName, List<T> list) where T : class { int val = 0; foreach (var item in list) { if (RecordAdd<T>(useDb, tbName, item)) val++; } return val; } /// <summary> /// 更新一条记录(实体第一个属性必须为主键) /// </summary>zlf 2015-02-26 /// <typeparam name="T">实体类 必须保证字段与数据库一致</typeparam> /// <param name="useDb">数据库</param> /// <param name="tbName">数据表名</param> /// <param name="info">数据实体</param> public static bool RecordUpdate<T>(string useDb, string tbName, T info) where T : class { if (String.IsNullOrEmpty(tbName) || info == null) { return false; } var type = typeof(T); var fields = type.GetProperties(); if (fields.Length < 2) { return false; } StringBuilder sb = new StringBuilder(); sb.Append("update " + tbName + " set "); List<SqlParameter> list = new List<SqlParameter>(); for (int i = 1; i < fields.Length; i++) { var p = fields[i]; var v = p.GetValue(info, null); if (i == 1) { sb.Append(p.Name + "=" + preParameter + p.Name); } else { sb.Append("," + p.Name + "=" + preParameter + p.Name); } list.Add(new SqlParameter(preParameter + p.Name, v)); } sb.Append(" where " + fields[0].Name + "=" + preParameter + fields[0].Name); list.Add(new SqlParameter(preParameter + fields[0].Name, fields[0].GetValue(info, null))); try { int rows = ExecuteNonQuery(useDb, sb.ToString(), list.ToArray()); return rows > 0; } catch { } return false; } /// <summary> /// 获取对象实体 /// </summary>zlf 2015-02-26 /// <typeparam name="T">实体类</typeparam> /// <param name="useDb">数据库</param> /// <param name="tbName">数据表名</param> /// <param name="strWhere">匹配条件</param> /// <returns>数据实体</returns> public static T GetModel<T>(string useDb, string tbName, string strWhere) where T : class { T val = null; if (!String.IsNullOrEmpty(tbName)) { StringBuilder strSql = new StringBuilder(); strSql.Append("select top 1 * from " + tbName); strWhere = CheckWhere(strWhere); if (!String.IsNullOrEmpty(strWhere)) { if (strWhere.StartsWith("order by")) { strSql.Append(" " + strWhere); } else { strSql.Append(" where " + strWhere); } } try { var connStr = GetConnectionString(useDb); if (String.IsNullOrEmpty(connStr)) return null; using (SqlConnection con = new SqlConnection(connStr)) { try { con.Open(); SqlCommand cmd = new SqlCommand(strSql.ToString(), con); using (IDataReader dataReader = cmd.ExecuteReader()) { if (dataReader.Read()) { var type = typeof(T); var fields = type.GetProperties();//实体属性集合 val = (T)Activator.CreateInstance(type); var columns = new List<string>();//数据列集合 for (int i = 0; i < dataReader.FieldCount; i++) { columns.Add(dataReader.GetName(i).ToLower()); } foreach (var p in fields) { //为实体赋值 if (columns.Contains(p.Name.ToLower())) { var ovalue = dataReader[p.Name]; if (ovalue == null) continue; var ptype = p.PropertyType; if (ptype.ToString().ToLower().Contains("int")) { p.SetValue(val, Convert.ToInt32(ovalue), null); } else { p.SetValue(val, ovalue, null); } continue; } } } con.Close(); } } catch (System.Data.SqlClient.SqlException e) { con.Close(); throw e; } } } catch //(Exception ex) { } } return val; } /// <summary> /// 获取实体集合 /// </summary>zlf 2015-02-26 /// <typeparam name="T">实体类</typeparam> /// <param name="useDb">数据库</param> /// <param name="tbName">数据表名</param> /// <param name="strWhere">匹配条件</param> /// <returns>满足条件的实体集</returns> public static List<T> GetInfoList<T>(string useDb, int top, string tbName, string strWhere) where T : class { var list = new List<T>(); if (String.IsNullOrEmpty(tbName)) { return list; } StringBuilder strSql = new StringBuilder(); strSql.Append("select top " + top + " * from " + tbName); strWhere = CheckWhere(strWhere); if (!String.IsNullOrEmpty(strWhere)) { if (strWhere.StartsWith("order by")) { strSql.Append(" " + strWhere); } else { strSql.Append(" where " + strWhere); } } try { var connStr = GetConnectionString(useDb); if (String.IsNullOrEmpty(connStr)) return null; using (SqlConnection con = new SqlConnection(connStr)) { try { con.Open(); SqlCommand cmd = new SqlCommand(strSql.ToString(), con); using (IDataReader dataReader = cmd.ExecuteReader()) { T val = null; while (dataReader.Read()) { var type = typeof(T); var fields = type.GetProperties();//实体属性集合 val = (T)Activator.CreateInstance(type); var columns = new List<string>();//数据列集合 for (int i = 0; i < dataReader.FieldCount; i++) { columns.Add(dataReader.GetName(i).ToLower()); } foreach (var p in fields) { //为实体赋值 if (columns.Contains(p.Name.ToLower())) { var ovalue = dataReader[p.Name]; if (ovalue == null) continue; var ptype = p.PropertyType; if (ptype.ToString().ToLower().Contains("int")) { p.SetValue(val, Convert.ToInt32(ovalue), null); } else { p.SetValue(val, ovalue, null); } continue; } } list.Add(val); } con.Close(); } } catch (System.Data.SqlClient.SqlException e) { con.Close(); throw e; } } } catch //(Exception ex) { } return list; } }
标签:
原文地址:http://www.cnblogs.com/mqly/p/4300915.html