MySqlHelper代码:

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Configuration;
  6. using System.Data;
  7. using MySql.Data.MySqlClient;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Web;
  12. using System.Xml.Linq;
  13. using System.Data.Objects.DataClasses;
  14. using Models;
  15. using System.Text.RegularExpressions;
  16.  
  17. namespace DBHelper
  18. {
  19. /// <summary>
  20. /// MySql操作类
  21. /// 2015年6月20日
  22. /// 写程序之前,首先引用MySql.Data.MySqlClient
  23. /// </summary>
  24. public class MySqlHelper
  25. {
  26. #region 静态变量
  27. /// <summary>
  28. /// 数据库连接字符串
  29. /// </summary>
  30. private static string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
  31. #endregion
  32.  
  33. #region MySqlConnection 获取数据库连接
  34. /// <summary>
  35. /// 获取数据库连接
  36. /// </summary>
  37. private static MySqlConnection GetConn()
  38. {
  39. MySqlConnection connection = null;
  40.  
  41. string key = "Simpo2016_MySqlConnection";
  42.  
  43. if (HttpContext.Current.Items[key] == null)
  44. {
  45. connection = new MySqlConnection(connectionString);
  46. connection.Open();
  47. HttpContext.Current.Items[key] = connection;
  48. }
  49. else
  50. {
  51. connection = (MySqlConnection)HttpContext.Current.Items[key];
  52. }
  53.  
  54. return connection;
  55. }
  56. #endregion
  57.  
  58. #region MySqlTransaction 获取事务对象
  59. /// <summary>
  60. /// 获取事务对象
  61. /// </summary>
  62. private static MySqlTransaction GetTran()
  63. {
  64. MySqlTransaction tran = null;
  65.  
  66. string key = "Simpo2016_MySqlTransaction";
  67.  
  68. if (HttpContext.Current.Items[key] == null)
  69. {
  70. tran = GetConn().BeginTransaction();
  71. HttpContext.Current.Items[key] = tran;
  72. }
  73. else
  74. {
  75. tran = (MySqlTransaction)HttpContext.Current.Items[key];
  76. }
  77.  
  78. return tran;
  79. }
  80. #endregion
  81.  
  82. #region 开起事务标志
  83. /// <summary>
  84. /// 事务标志
  85. /// </summary>
  86. private static string tranFlagKey = "Simpo2016_MySqlTransaction_Flag";
  87. /// <summary>
  88. /// 添加事务标志
  89. /// </summary>
  90. public static void AddTranFlag()
  91. {
  92. HttpContext.Current.Items[tranFlagKey] = true;
  93. }
  94. /// <summary>
  95. /// 移除事务标志
  96. /// </summary>
  97. public static void RemoveTranFlag()
  98. {
  99. HttpContext.Current.Items[tranFlagKey] = false;
  100. }
  101. /// <summary>
  102. /// 事务标志
  103. /// </summary>
  104. public static bool TranFlag
  105. {
  106. get
  107. {
  108. bool tranFlag = false;
  109.  
  110. if (HttpContext.Current.Items[tranFlagKey] != null)
  111. {
  112. tranFlag = (bool)HttpContext.Current.Items[tranFlagKey];
  113. }
  114.  
  115. return tranFlag;
  116. }
  117. }
  118. #endregion
  119.  
  120. #region 用于查询的数据库连接
  121. /// <summary>
  122. /// 用于查询的数据库连接
  123. /// </summary>
  124. private MySqlConnection m_Conn;
  125. #endregion
  126.  
  127. #region 构造函数
  128. public MySqlHelper()
  129. {
  130. m_Conn = new MySqlConnection(connectionString);
  131. }
  132. #endregion
  133.  
  134. #region 基础方法
  135. #region 执行简单SQL语句
  136. #region Exists
  137. public bool Exists(string sqlString)
  138. {
  139. using (MySqlCommand cmd = new MySqlCommand(sqlString, m_Conn))
  140. {
  141. try
  142. {
  143. m_Conn.Open();
  144. object obj = cmd.ExecuteScalar();
  145. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  146. {
  147. return false;
  148. }
  149. else
  150. {
  151. return true;
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. throw ex;
  157. }
  158. finally
  159. {
  160. cmd.Dispose();
  161. m_Conn.Close();
  162. }
  163. }
  164. }
  165. #endregion
  166.  
  167. #region 执行SQL语句,返回影响的记录数
  168. /// <summary>
  169. /// 执行SQL语句,返回影响的记录数
  170. /// </summary>
  171. /// <param name="sqlString">SQL语句</param>
  172. /// <returns>影响的记录数</returns>
  173. public int ExecuteSql(string sqlString)
  174. {
  175. MySqlConnection connection = GetConn();
  176. using (MySqlCommand cmd = new MySqlCommand(sqlString, connection))
  177. {
  178. try
  179. {
  180. if (connection.State != ConnectionState.Open) connection.Open();
  181. if (TranFlag) cmd.Transaction = GetTran();
  182. int rows = cmd.ExecuteNonQuery();
  183. return rows;
  184. }
  185. catch (Exception ex)
  186. {
  187. throw new Exception(ex.Message);
  188. }
  189. finally
  190. {
  191. cmd.Dispose();
  192. if (!TranFlag) connection.Close();
  193. }
  194. }
  195. }
  196. #endregion
  197.  
  198. #region 执行一条计算查询结果语句,返回查询结果
  199. /// <summary>
  200. /// 执行一条计算查询结果语句,返回查询结果(object)
  201. /// </summary>
  202. /// <param name="sqlString">计算查询结果语句</param>
  203. /// <returns>查询结果(object)</returns>
  204. public object GetSingle(string sqlString)
  205. {
  206. using (MySqlCommand cmd = new MySqlCommand(sqlString, m_Conn))
  207. {
  208. try
  209. {
  210. m_Conn.Open();
  211. object obj = cmd.ExecuteScalar();
  212. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  213. {
  214. return null;
  215. }
  216. else
  217. {
  218. return obj;
  219. }
  220. }
  221. catch (Exception ex)
  222. {
  223. throw ex;
  224. }
  225. finally
  226. {
  227. cmd.Dispose();
  228. m_Conn.Close();
  229. }
  230. }
  231. }
  232. #endregion
  233.  
  234. #region 执行查询语句,返回SQLiteDataReader
  235. /// <summary>
  236. /// 执行查询语句,返回SQLiteDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
  237. /// </summary>
  238. /// <param name="sqlString">查询语句</param>
  239. /// <returns>SQLiteDataReader</returns>
  240. public MySqlDataReader ExecuteReader(string sqlString)
  241. {
  242. MySqlConnection connection = new MySqlConnection(connectionString);
  243. MySqlCommand cmd = new MySqlCommand(sqlString, connection);
  244. try
  245. {
  246. connection.Open();
  247. MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  248. return myReader;
  249. }
  250. catch (Exception ex)
  251. {
  252. throw ex;
  253. }
  254. }
  255. #endregion
  256.  
  257. #region 执行查询语句,返回DataSet
  258. /// <summary>
  259. /// 执行查询语句,返回DataSet
  260. /// </summary>
  261. /// <param name="sqlString">查询语句</param>
  262. /// <returns>DataSet</returns>
  263. public DataSet Query(string sqlString)
  264. {
  265. using (MySqlConnection connection = new MySqlConnection(connectionString))
  266. {
  267. DataSet ds = new DataSet();
  268. try
  269. {
  270. connection.Open();
  271. MySqlDataAdapter command = new MySqlDataAdapter(sqlString, connection);
  272. command.Fill(ds, "ds");
  273. }
  274. catch (Exception ex)
  275. {
  276. throw ex;
  277. }
  278. finally
  279. {
  280. connection.Close();
  281. }
  282. return ds;
  283. }
  284. }
  285. #endregion
  286. #endregion
  287.  
  288. #region 执行带参数的SQL语句
  289. #region 执行SQL语句,返回影响的记录数
  290. /// <summary>
  291. /// 执行SQL语句,返回影响的记录数
  292. /// </summary>
  293. /// <param name="SQLString">SQL语句</param>
  294. /// <returns>影响的记录数</returns>
  295. public int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
  296. {
  297. MySqlConnection connection = GetConn();
  298. using (MySqlCommand cmd = new MySqlCommand())
  299. {
  300. try
  301. {
  302. PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  303. if (TranFlag) cmd.Transaction = GetTran();
  304. int rows = cmd.ExecuteNonQuery();
  305. cmd.Parameters.Clear();
  306. return rows;
  307. }
  308. catch (Exception ex)
  309. {
  310. throw ex;
  311. }
  312. finally
  313. {
  314. cmd.Dispose();
  315. if (!TranFlag) connection.Close();
  316. }
  317. }
  318. }
  319. #endregion
  320.  
  321. #region 执行查询语句,返回SQLiteDataReader
  322. /// <summary>
  323. /// 执行查询语句,返回SQLiteDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
  324. /// </summary>
  325. /// <param name="strSQL">查询语句</param>
  326. /// <returns>SQLiteDataReader</returns>
  327. public MySqlDataReader ExecuteReader(string sqlString, params MySqlParameter[] cmdParms)
  328. {
  329. MySqlCommand cmd = new MySqlCommand();
  330. try
  331. {
  332. PrepareCommand(cmd, m_Conn, null, sqlString, cmdParms);
  333. MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  334. cmd.Parameters.Clear();
  335. return myReader;
  336. }
  337. catch (Exception ex)
  338. {
  339. throw ex;
  340. }
  341.  
  342. }
  343. #endregion
  344.  
  345. #region 执行查询语句,返回DataSet
  346. /// <summary>
  347. /// 执行查询语句,返回DataSet
  348. /// </summary>
  349. /// <param name="sqlString">查询语句</param>
  350. /// <returns>DataSet</returns>
  351. public DataSet Query(string sqlString, params MySqlParameter[] cmdParms)
  352. {
  353. MySqlCommand cmd = new MySqlCommand();
  354. PrepareCommand(cmd, m_Conn, null, sqlString, cmdParms);
  355. using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
  356. {
  357. DataSet ds = new DataSet();
  358. try
  359. {
  360. da.Fill(ds, "ds");
  361. cmd.Parameters.Clear();
  362. }
  363. catch (Exception ex)
  364. {
  365. throw ex;
  366. }
  367. finally
  368. {
  369. cmd.Dispose();
  370. m_Conn.Close();
  371. }
  372. return ds;
  373. }
  374. }
  375. #endregion
  376.  
  377. #region PrepareCommand
  378. private void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
  379. {
  380. if (conn.State != ConnectionState.Open) conn.Open();
  381. cmd.Connection = conn;
  382. cmd.CommandText = cmdText;
  383. if (trans != null) cmd.Transaction = trans;
  384. cmd.CommandType = CommandType.Text;
  385. if (cmdParms != null)
  386. {
  387. foreach (MySqlParameter parm in cmdParms)
  388. {
  389. cmd.Parameters.Add(parm);
  390. }
  391. }
  392. }
  393. #endregion
  394. #endregion
  395. #endregion
  396.  
  397. #region 增删改查
  398. #region 获取最大编号
  399. /// <summary>
  400. /// 获取最大编号
  401. /// </summary>
  402. /// <typeparam name="T">实体Model</typeparam>
  403. /// <param name="key">主键</param>
  404. public int GetMaxID<T>(string key)
  405. {
  406. Type type = typeof(T);
  407.  
  408. string sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
  409. using (MySqlCommand cmd = new MySqlCommand(sql, m_Conn))
  410. {
  411. try
  412. {
  413. m_Conn.Open();
  414. object obj = cmd.ExecuteScalar();
  415. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  416. {
  417. return ;
  418. }
  419. else
  420. {
  421. return int.Parse(obj.ToString()) + ;
  422. }
  423. }
  424. catch (Exception ex)
  425. {
  426. throw ex;
  427. }
  428. finally
  429. {
  430. cmd.Dispose();
  431. m_Conn.Close();
  432. }
  433. }
  434. }
  435. #endregion
  436.  
  437. #region 添加
  438. /// <summary>
  439. /// 添加
  440. /// </summary>
  441. public void Insert(object obj)
  442. {
  443. StringBuilder strSql = new StringBuilder();
  444. Type type = obj.GetType();
  445. CacheHelper.Remove(type);//删除缓存
  446. strSql.Append(string.Format("insert into {0}(", type.Name));
  447.  
  448. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  449. List<string> propertyNameList = new List<string>();
  450. foreach (PropertyInfo propertyInfo in propertyInfoList)
  451. {
  452. propertyNameList.Add(propertyInfo.Name);
  453. }
  454.  
  455. strSql.Append(string.Format("{0})", string.Join(",", propertyNameList.ToArray())));
  456. strSql.Append(string.Format(" values ({0})", string.Join(",", propertyNameList.ConvertAll<string>(a => "@" + a).ToArray())));
  457. MySqlParameter[] parameters = new MySqlParameter[propertyInfoList.Length];
  458. for (int i = ; i < propertyInfoList.Length; i++)
  459. {
  460. PropertyInfo propertyInfo = propertyInfoList[i];
  461. object val = propertyInfo.GetValue(obj, null);
  462. MySqlParameter param = new MySqlParameter("@" + propertyInfo.Name, val == null ? DBNull.Value : val);
  463. parameters[i] = param;
  464. }
  465.  
  466. ExecuteSql(strSql.ToString(), parameters);
  467. }
  468. #endregion
  469.  
  470. #region 修改
  471. /// <summary>
  472. /// 修改
  473. /// </summary>
  474. public void Update(object obj)
  475. {
  476. object oldObj = Find(obj, false);
  477. if (oldObj == null) throw new Exception("无法获取到旧数据");
  478.  
  479. StringBuilder strSql = new StringBuilder();
  480. Type type = obj.GetType();
  481. CacheHelper.Remove(type);//删除缓存
  482. strSql.Append(string.Format("update {0} ", type.Name));
  483.  
  484. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  485. List<string> propertyNameList = new List<string>();
  486. int savedCount = ;
  487. foreach (PropertyInfo propertyInfo in propertyInfoList)
  488. {
  489. object oldVal = propertyInfo.GetValue(oldObj, null);
  490. object val = propertyInfo.GetValue(obj, null);
  491. if (!object.Equals(oldVal, val))
  492. {
  493. propertyNameList.Add(propertyInfo.Name);
  494. savedCount++;
  495. }
  496. }
  497.  
  498. strSql.Append(string.Format(" set "));
  499. MySqlParameter[] parameters = new MySqlParameter[savedCount];
  500. StringBuilder sbPros = new StringBuilder();
  501. int k = ;
  502. for (int i = ; i < propertyInfoList.Length; i++)
  503. {
  504. PropertyInfo propertyInfo = propertyInfoList[i];
  505. object oldVal = propertyInfo.GetValue(oldObj, null);
  506. object val = propertyInfo.GetValue(obj, null);
  507. if (!object.Equals(oldVal, val))
  508. {
  509. sbPros.Append(string.Format(" {0}=@{0},", propertyInfo.Name));
  510. MySqlParameter param = new MySqlParameter("@" + propertyInfo.Name, val == null ? DBNull.Value : val);
  511. parameters[k++] = param;
  512. }
  513. }
  514. if (sbPros.Length > )
  515. {
  516. strSql.Append(sbPros.ToString(, sbPros.Length - ));
  517. }
  518. strSql.Append(string.Format(" where {0}='{1}'", GetIdName(obj.GetType()), GetIdVal(obj).ToString()));
  519.  
  520. if (savedCount > )
  521. {
  522. ExecuteSql(strSql.ToString(), parameters);
  523. }
  524. }
  525. #endregion
  526.  
  527. #region 删除
  528. /// <summary>
  529. /// 根据Id删除
  530. /// </summary>
  531. public void Delete<T>(int id)
  532. {
  533. Type type = typeof(T);
  534. CacheHelper.Remove(type);//删除缓存
  535. StringBuilder sbSql = new StringBuilder();
  536. sbSql.Append(string.Format("delete from {0} where {2}='{1}'", type.Name, id, GetIdName(type)));
  537.  
  538. ExecuteSql(sbSql.ToString());
  539. }
  540. /// <summary>
  541. /// 根据Id集合删除
  542. /// </summary>
  543. public void BatchDelete<T>(string ids)
  544. {
  545. if (string.IsNullOrWhiteSpace(ids)) return;
  546.  
  547. Type type = typeof(T);
  548. CacheHelper.Remove(type);//删除缓存
  549. StringBuilder sbSql = new StringBuilder();
  550. sbSql.Append(string.Format("delete from {0} where {2} in ({1})", type.Name, ids, GetIdName(type)));
  551.  
  552. ExecuteSql(sbSql.ToString());
  553. }
  554. /// <summary>
  555. /// 根据条件删除
  556. /// </summary>
  557. public void Delete<T>(string conditions)
  558. {
  559. if (string.IsNullOrWhiteSpace(conditions)) return;
  560.  
  561. Type type = typeof(T);
  562. CacheHelper.Remove(type);//删除缓存
  563. StringBuilder sbSql = new StringBuilder();
  564. sbSql.Append(string.Format("delete from {0} where {1}", type.Name, conditions));
  565.  
  566. ExecuteSql(sbSql.ToString());
  567. }
  568. #endregion
  569.  
  570. #region 获取实体
  571. #region 根据实体获取实体
  572. /// <summary>
  573. /// 根据实体获取实体
  574. /// </summary>
  575. private object Find(object obj, bool readCache = true)
  576. {
  577. Type type = obj.GetType();
  578.  
  579. object result = Activator.CreateInstance(type);
  580. bool hasValue = false;
  581. IDataReader rd = null;
  582.  
  583. string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, GetIdVal(obj), GetIdName(obj.GetType()));
  584. //获取缓存
  585. if (readCache && CacheHelper.Exists(type, sql))
  586. {
  587. return CacheHelper.Get(type, sql);
  588. }
  589.  
  590. try
  591. {
  592. rd = ExecuteReader(sql);
  593.  
  594. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  595.  
  596. int fcnt = rd.FieldCount;
  597. List<string> fileds = new List<string>();
  598. for (int i = ; i < fcnt; i++)
  599. {
  600. fileds.Add(rd.GetName(i).ToUpper());
  601. }
  602.  
  603. while (rd.Read())
  604. {
  605. hasValue = true;
  606. IDataRecord record = rd;
  607.  
  608. foreach (PropertyInfo pro in propertyInfoList)
  609. {
  610. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  611. {
  612. continue;
  613. }
  614.  
  615. pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  616. }
  617. }
  618. }
  619. catch (Exception ex)
  620. {
  621. throw ex;
  622. }
  623. finally
  624. {
  625. if (rd != null && !rd.IsClosed)
  626. {
  627. rd.Close();
  628. rd.Dispose();
  629. }
  630. }
  631.  
  632. if (hasValue)
  633. {
  634. CacheHelper.Add(type, sql, result);//添加缓存
  635. return result;
  636. }
  637. else
  638. {
  639. return null;
  640. }
  641. }
  642. #endregion
  643.  
  644. #region 根据Id获取实体
  645. /// <summary>
  646. /// 根据Id获取实体
  647. /// </summary>
  648. private object FindById(Type type, int id)
  649. {
  650. object result = Activator.CreateInstance(type);
  651. IDataReader rd = null;
  652. bool hasValue = false;
  653.  
  654. string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));
  655. //获取缓存
  656. if (CacheHelper.Exists(type, sql))
  657. {
  658. return CacheHelper.Get(type, sql);
  659. }
  660.  
  661. try
  662. {
  663. rd = ExecuteReader(sql);
  664.  
  665. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  666.  
  667. int fcnt = rd.FieldCount;
  668. List<string> fileds = new List<string>();
  669. for (int i = ; i < fcnt; i++)
  670. {
  671. fileds.Add(rd.GetName(i).ToUpper());
  672. }
  673.  
  674. while (rd.Read())
  675. {
  676. hasValue = true;
  677. IDataRecord record = rd;
  678.  
  679. foreach (PropertyInfo pro in propertyInfoList)
  680. {
  681. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  682. {
  683. continue;
  684. }
  685.  
  686. pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  687. }
  688. }
  689. }
  690. catch (Exception ex)
  691. {
  692. throw ex;
  693. }
  694. finally
  695. {
  696. if (rd != null && !rd.IsClosed)
  697. {
  698. rd.Close();
  699. rd.Dispose();
  700. }
  701. }
  702.  
  703. if (hasValue)
  704. {
  705. CacheHelper.Add(type, sql, result);//添加缓存
  706. return result;
  707. }
  708. else
  709. {
  710. return null;
  711. }
  712. }
  713. #endregion
  714.  
  715. #region 根据Id获取实体
  716. /// <summary>
  717. /// 根据Id获取实体
  718. /// </summary>
  719. public T FindById<T>(string id) where T : new()
  720. {
  721. Type type = typeof(T);
  722. T result = (T)Activator.CreateInstance(type);
  723. IDataReader rd = null;
  724. bool hasValue = false;
  725.  
  726. string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));
  727. //获取缓存
  728. if (CacheHelper.Exists(type, sql))
  729. {
  730. return (T)CacheHelper.Get(type, sql);
  731. }
  732.  
  733. try
  734. {
  735. rd = ExecuteReader(sql);
  736.  
  737. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  738.  
  739. int fcnt = rd.FieldCount;
  740. List<string> fileds = new List<string>();
  741. for (int i = ; i < fcnt; i++)
  742. {
  743. fileds.Add(rd.GetName(i).ToUpper());
  744. }
  745.  
  746. while (rd.Read())
  747. {
  748. hasValue = true;
  749. IDataRecord record = rd;
  750.  
  751. foreach (PropertyInfo pro in propertyInfoList)
  752. {
  753. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  754. {
  755. continue;
  756. }
  757.  
  758. pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  759. }
  760. }
  761. }
  762. catch (Exception ex)
  763. {
  764. throw ex;
  765. }
  766. finally
  767. {
  768. if (rd != null && !rd.IsClosed)
  769. {
  770. rd.Close();
  771. rd.Dispose();
  772. }
  773. }
  774.  
  775. if (hasValue)
  776. {
  777. CacheHelper.Add(type, sql, result);//添加缓存
  778. return result;
  779. }
  780. else
  781. {
  782. return default(T);
  783. }
  784. }
  785. #endregion
  786.  
  787. #region 根据sql获取实体
  788. /// <summary>
  789. /// 根据sql获取实体
  790. /// </summary>
  791. public T FindBySql<T>(string sql) where T : new()
  792. {
  793. Type type = typeof(T);
  794. T result = (T)Activator.CreateInstance(type);
  795. IDataReader rd = null;
  796. bool hasValue = false;
  797.  
  798. //获取缓存
  799. if (CacheHelper.Exists(type, sql))
  800. {
  801. return (T)CacheHelper.Get(type, sql);
  802. }
  803.  
  804. try
  805. {
  806. rd = ExecuteReader(sql);
  807.  
  808. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  809.  
  810. int fcnt = rd.FieldCount;
  811. List<string> fileds = new List<string>();
  812. for (int i = ; i < fcnt; i++)
  813. {
  814. fileds.Add(rd.GetName(i).ToUpper());
  815. }
  816.  
  817. while (rd.Read())
  818. {
  819. hasValue = true;
  820. IDataRecord record = rd;
  821.  
  822. foreach (PropertyInfo pro in propertyInfoList)
  823. {
  824. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  825. {
  826. continue;
  827. }
  828.  
  829. pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  830. }
  831. }
  832. }
  833. catch (Exception ex)
  834. {
  835. throw ex;
  836. }
  837. finally
  838. {
  839. if (rd != null && !rd.IsClosed)
  840. {
  841. rd.Close();
  842. rd.Dispose();
  843. }
  844. }
  845.  
  846. if (hasValue)
  847. {
  848. CacheHelper.Add(type, sql, result);//添加缓存
  849. return result;
  850. }
  851. else
  852. {
  853. return default(T);
  854. }
  855. }
  856. #endregion
  857. #endregion
  858.  
  859. #region 获取列表
  860. /// <summary>
  861. /// 获取列表
  862. /// </summary>
  863. public List<T> FindListBySql<T>(string sql) where T : new()
  864. {
  865. List<T> list = new List<T>();
  866. object obj;
  867. IDataReader rd = null;
  868.  
  869. //获取缓存
  870. Type type = GetBaseType(typeof(T));
  871. if (CacheHelper.Exists(type, sql))
  872. {
  873. return (List<T>)CacheHelper.Get(type, sql);
  874. }
  875.  
  876. try
  877. {
  878. rd = ExecuteReader(sql);
  879.  
  880. if (typeof(T) == typeof(int))
  881. {
  882. while (rd.Read())
  883. {
  884. list.Add((T)rd[]);
  885. }
  886. }
  887. else if (typeof(T) == typeof(string))
  888. {
  889. while (rd.Read())
  890. {
  891. list.Add((T)rd[]);
  892. }
  893. }
  894. else
  895. {
  896. PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();
  897.  
  898. int fcnt = rd.FieldCount;
  899. List<string> fileds = new List<string>();
  900. for (int i = ; i < fcnt; i++)
  901. {
  902. fileds.Add(rd.GetName(i).ToUpper());
  903. }
  904.  
  905. while (rd.Read())
  906. {
  907. IDataRecord record = rd;
  908. obj = new T();
  909.  
  910. foreach (PropertyInfo pro in propertyInfoList)
  911. {
  912. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  913. {
  914. continue;
  915. }
  916.  
  917. pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  918. }
  919. list.Add((T)obj);
  920. }
  921. }
  922. }
  923. catch (Exception ex)
  924. {
  925. throw ex;
  926. }
  927. finally
  928. {
  929. if (rd != null && !rd.IsClosed)
  930. {
  931. rd.Close();
  932. rd.Dispose();
  933. }
  934. }
  935.  
  936. CacheHelper.Add(type, sql, list);//添加缓存
  937. return list;
  938. }
  939. #endregion
  940.  
  941. #region 获取列表
  942. /// <summary>
  943. /// 获取列表
  944. /// </summary>
  945. public List<T> FindListBySql<T>(string sql, params MySqlParameter[] cmdParms) where T : new()
  946. {
  947. List<T> list = new List<T>();
  948. object obj;
  949. IDataReader rd = null;
  950.  
  951. //获取缓存
  952. Type type = GetBaseType(typeof(T));
  953. if (CacheHelper.Exists(type, sql))
  954. {
  955. return (List<T>)CacheHelper.Get(type, sql);
  956. }
  957.  
  958. try
  959. {
  960. rd = ExecuteReader(sql, cmdParms);
  961.  
  962. if (typeof(T) == typeof(int))
  963. {
  964. while (rd.Read())
  965. {
  966. list.Add((T)rd[]);
  967. }
  968. }
  969. else if (typeof(T) == typeof(string))
  970. {
  971. while (rd.Read())
  972. {
  973. list.Add((T)rd[]);
  974. }
  975. }
  976. else
  977. {
  978. PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();
  979.  
  980. int fcnt = rd.FieldCount;
  981. List<string> fileds = new List<string>();
  982. for (int i = ; i < fcnt; i++)
  983. {
  984. fileds.Add(rd.GetName(i).ToUpper());
  985. }
  986.  
  987. while (rd.Read())
  988. {
  989. IDataRecord record = rd;
  990. obj = new T();
  991.  
  992. foreach (PropertyInfo pro in propertyInfoList)
  993. {
  994. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  995. {
  996. continue;
  997. }
  998.  
  999. pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  1000. }
  1001. list.Add((T)obj);
  1002. }
  1003. }
  1004. }
  1005. catch (Exception ex)
  1006. {
  1007. throw ex;
  1008. }
  1009. finally
  1010. {
  1011. if (rd != null && !rd.IsClosed)
  1012. {
  1013. rd.Close();
  1014. rd.Dispose();
  1015. }
  1016. }
  1017.  
  1018. CacheHelper.Add(type, sql, list);//添加缓存
  1019. return list;
  1020. }
  1021. #endregion
  1022.  
  1023. #region 分页获取列表
  1024. /// <summary>
  1025. /// 分页(任意entity,尽量少的字段)
  1026. /// </summary>
  1027. public PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage) where T : new()
  1028. {
  1029. PagerModel pagerModel = new PagerModel(currentPage, pageSize);
  1030.  
  1031. //获取缓存
  1032. string cacheKey = string.Format("sql:{0},orderby:{1},pageSize:{2},currentPage:{3}", sql, orderby, pageSize, currentPage);
  1033. Type type = GetBaseType(typeof(T));
  1034. if (CacheHelper.Exists(type, cacheKey))
  1035. {
  1036. return (PagerModel)CacheHelper.Get(type, cacheKey);
  1037. }
  1038.  
  1039. using (MySqlConnection connection = new MySqlConnection(connectionString))
  1040. {
  1041. connection.Open();
  1042. string commandText = string.Format("select count(*) from ({0}) T", sql);
  1043. IDbCommand cmd = new MySqlCommand(commandText, connection);
  1044. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1045.  
  1046. int startRow = pageSize * (currentPage - );
  1047.  
  1048. StringBuilder sb = new StringBuilder();
  1049. sb.Append("select * from (");
  1050. sb.Append(sql);
  1051. if (!string.IsNullOrWhiteSpace(orderby))
  1052. {
  1053. sb.Append(" ");
  1054. sb.Append(orderby);
  1055. }
  1056. sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
  1057.  
  1058. List<T> list = FindListBySql<T>(sb.ToString());
  1059. pagerModel.result = list;
  1060. }
  1061.  
  1062. CacheHelper.Add(type, cacheKey, pagerModel);
  1063. return pagerModel;
  1064. }
  1065. #endregion
  1066.  
  1067. #region 分页获取列表
  1068. /// <summary>
  1069. /// 分页(任意entity,尽量少的字段)
  1070. /// </summary>
  1071. /// <typeparam name="T"></typeparam>
  1072. /// <param name="sql"></param>
  1073. /// <returns></returns>
  1074. public PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage, params MySqlParameter[] cmdParms) where T : new()
  1075. {
  1076. PagerModel pagerModel = new PagerModel(currentPage, pageSize);
  1077.  
  1078. //获取缓存
  1079. string cacheKey = string.Format("sql:{0},orderby:{1},pageSize:{2},currentPage:{3}", sql, orderby, pageSize, currentPage);
  1080. Type type = GetBaseType(typeof(T));
  1081. if (CacheHelper.Exists(type, cacheKey))
  1082. {
  1083. return (PagerModel)CacheHelper.Get(type, cacheKey);
  1084. }
  1085.  
  1086. using (MySqlConnection connection = new MySqlConnection(connectionString))
  1087. {
  1088. connection.Open();
  1089. string commandText = string.Format("select count(*) from ({0}) T", sql);
  1090. MySqlCommand cmd = new MySqlCommand(commandText, connection);
  1091. PrepareCommand(cmd, connection, null, commandText, cmdParms);
  1092. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1093. cmd.Parameters.Clear();
  1094.  
  1095. int startRow = pageSize * (currentPage - );
  1096.  
  1097. StringBuilder sb = new StringBuilder();
  1098. sb.Append("select * from (");
  1099. sb.Append(sql);
  1100. if (!string.IsNullOrWhiteSpace(orderby))
  1101. {
  1102. sb.Append(" ");
  1103. sb.Append(orderby);
  1104. }
  1105. sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
  1106.  
  1107. List<T> list = FindListBySql<T>(sb.ToString(), cmdParms);
  1108. pagerModel.result = list;
  1109. }
  1110.  
  1111. CacheHelper.Add(type, cacheKey, pagerModel);
  1112. return pagerModel;
  1113. }
  1114.  
  1115. #endregion
  1116.  
  1117. #region 分页获取列表
  1118. /// <summary>
  1119. /// 分页(任意entity,尽量少的字段)
  1120. /// </summary>
  1121. public DataSet FindPageBySql(string sql, string orderby, int pageSize, int currentPage, out int totalCount, params MySqlParameter[] cmdParms)
  1122. {
  1123. DataSet ds = null;
  1124.  
  1125. //获取缓存
  1126. string cacheKey = string.Format("sql:{0},orderby:{1},pageSize:{2},currentPage:{3}", sql, orderby, pageSize, currentPage);
  1127. Regex reg = new Regex(@"from[\s]+([^\(\),\s]+)", RegexOptions.IgnoreCase);
  1128. Match match = reg.Match(sql);
  1129. string tableName = match.Groups[].Value;
  1130. Dictionary<string, object> dic;
  1131. if (CacheHelper.Exists(tableName, cacheKey))
  1132. {
  1133. dic = (Dictionary<string, object>)CacheHelper.Get(tableName, cacheKey);
  1134. totalCount = (int)dic["totalCount"];
  1135. return (DataSet)dic["DataSet"];
  1136. }
  1137.  
  1138. using (MySqlConnection connection = new MySqlConnection(connectionString))
  1139. {
  1140. connection.Open();
  1141. string commandText = string.Format("select count(*) from ({0}) T", sql);
  1142. IDbCommand cmd = new MySqlCommand(commandText, connection);
  1143. totalCount = int.Parse(cmd.ExecuteScalar().ToString());
  1144.  
  1145. int startRow = pageSize * (currentPage - );
  1146.  
  1147. StringBuilder sb = new StringBuilder();
  1148. sb.Append("select * from (");
  1149. sb.Append(sql);
  1150. if (!string.IsNullOrWhiteSpace(orderby))
  1151. {
  1152. sb.Append(" ");
  1153. sb.Append(orderby);
  1154. }
  1155. sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
  1156.  
  1157. ds = Query(sql, cmdParms);
  1158. }
  1159.  
  1160. dic = new Dictionary<string, object>();
  1161. dic.Add("totalCount", totalCount);
  1162. dic.Add("DataSet", ds);
  1163. CacheHelper.Add(tableName, cacheKey, dic);
  1164. return ds;
  1165. }
  1166. #endregion
  1167.  
  1168. #region getReaderValue 转换数据
  1169. /// <summary>
  1170. /// 转换数据
  1171. /// </summary>
  1172. private Object getReaderValue(Object rdValue, Type ptype)
  1173. {
  1174. if (ptype == typeof(double))
  1175. return Convert.ToDouble(rdValue);
  1176.  
  1177. if (ptype == typeof(decimal))
  1178. return Convert.ToDecimal(rdValue);
  1179.  
  1180. if (ptype == typeof(int))
  1181. return Convert.ToInt32(rdValue);
  1182.  
  1183. if (ptype == typeof(long))
  1184. return Convert.ToInt64(rdValue);
  1185.  
  1186. if (ptype == typeof(DateTime))
  1187. return Convert.ToDateTime(rdValue);
  1188.  
  1189. if (ptype == typeof(Nullable<double>))
  1190. return Convert.ToDouble(rdValue);
  1191.  
  1192. if (ptype == typeof(Nullable<decimal>))
  1193. return Convert.ToDecimal(rdValue);
  1194.  
  1195. if (ptype == typeof(Nullable<int>))
  1196. return Convert.ToInt32(rdValue);
  1197.  
  1198. if (ptype == typeof(Nullable<long>))
  1199. return Convert.ToInt64(rdValue);
  1200.  
  1201. if (ptype == typeof(Nullable<DateTime>))
  1202. return Convert.ToDateTime(rdValue);
  1203.  
  1204. return rdValue;
  1205. }
  1206. #endregion
  1207.  
  1208. #region 获取主键名称
  1209. /// <summary>
  1210. /// 获取主键名称
  1211. /// </summary>
  1212. public string GetIdName(Type type)
  1213. {
  1214. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  1215. foreach (PropertyInfo propertyInfo in propertyInfoList)
  1216. {
  1217. if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > )
  1218. {
  1219. return propertyInfo.Name;
  1220. }
  1221. }
  1222. return "Id";
  1223. }
  1224. #endregion
  1225.  
  1226. #region 获取主键值
  1227. /// <summary>
  1228. /// 获取主键名称
  1229. /// </summary>
  1230. public object GetIdVal(object val)
  1231. {
  1232. string idName = GetIdName(val.GetType());
  1233. if (!string.IsNullOrWhiteSpace(idName))
  1234. {
  1235. return val.GetType().GetProperty(idName).GetValue(val, null);
  1236. }
  1237. return ;
  1238. }
  1239. #endregion
  1240.  
  1241. #region 获取实体类属性
  1242. /// <summary>
  1243. /// 获取实体类属性
  1244. /// </summary>
  1245. private PropertyInfo[] GetEntityProperties(Type type)
  1246. {
  1247. List<PropertyInfo> result = new List<PropertyInfo>();
  1248. PropertyInfo[] propertyInfoList = type.GetProperties();
  1249. foreach (PropertyInfo propertyInfo in propertyInfoList)
  1250. {
  1251. if (propertyInfo.GetCustomAttributes(typeof(EdmRelationshipNavigationPropertyAttribute), false).Length ==
  1252. && propertyInfo.GetCustomAttributes(typeof(BrowsableAttribute), false).Length == )
  1253. {
  1254. result.Add(propertyInfo);
  1255. }
  1256. }
  1257. return result.ToArray();
  1258. }
  1259. #endregion
  1260.  
  1261. #region 获取基类
  1262. /// <summary>
  1263. /// 获取基类
  1264. /// </summary>
  1265. public Type GetBaseType(Type type)
  1266. {
  1267. while (type.BaseType != null && type.BaseType.Name != typeof(Object).Name)
  1268. {
  1269. type = type.BaseType;
  1270. }
  1271. return type;
  1272. }
  1273. #endregion
  1274. #endregion
  1275.  
  1276. #region 事务
  1277. #region 开始事务
  1278. /// <summary>
  1279. /// 开始事务
  1280. /// </summary>
  1281. public static void BeginTransaction()
  1282. {
  1283. GetTran();
  1284. AddTranFlag();
  1285. }
  1286. #endregion
  1287.  
  1288. #region 提交事务
  1289. /// <summary>
  1290. /// 提交事务
  1291. /// </summary>
  1292. public static void CommitTransaction()
  1293. {
  1294. try
  1295. {
  1296. if (GetConn().State == ConnectionState.Open)
  1297. {
  1298. GetTran().Commit();
  1299. RemoveTranFlag();
  1300. }
  1301. }
  1302. catch (Exception ex)
  1303. {
  1304. GetTran().Rollback();
  1305. RemoveTranFlag();
  1306. }
  1307. finally
  1308. {
  1309. if (GetConn().State == ConnectionState.Open) GetConn().Close();
  1310. }
  1311. }
  1312. #endregion
  1313.  
  1314. #region 回滚事务(出错时调用该方法回滚)
  1315. /// <summary>
  1316. /// 回滚事务(出错时调用该方法回滚)
  1317. /// </summary>
  1318. public static void RollbackTransaction()
  1319. {
  1320. GetTran().Rollback();
  1321. RemoveTranFlag();
  1322. GetConn().Close();
  1323. }
  1324. #endregion
  1325. #endregion
  1326.  
  1327. }
  1328. }

CacheHelper代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.Objects.DataClasses;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Web;
  11. using System.Web.Caching;
  12.  
  13. namespace DBHelper
  14. {
  15. /// <summary>
  16. /// 缓存类
  17. /// </summary>
  18. public static class CacheHelper
  19. {
  20. #region 变量
  21. /// <summary>
  22. /// 缓存整个页面的键
  23. /// </summary>
  24. public static string pageCacheKey = "pageCacheKey";
  25. #endregion
  26.  
  27. #region 是否存在
  28. /// <summary>
  29. /// 是否存在
  30. /// </summary>
  31. public static bool Exists<T>(string key)
  32. {
  33. return Exists(typeof(T).Name, key);
  34. }
  35. /// <summary>
  36. /// 是否存在
  37. /// </summary>
  38. public static bool Exists(Type type, string key)
  39. {
  40. return Exists(type.Name, key);
  41. }
  42. /// <summary>
  43. /// 是否存在
  44. /// </summary>
  45. public static bool Exists(string tableName, string key)
  46. {
  47. return false; //禁用缓存
  48. if (HttpRuntime.Cache[tableName] != null)
  49. {
  50. Dictionary<string, object> dic = (Dictionary<string, object>)HttpRuntime.Cache[tableName];
  51. if (dic.Keys.Contains<string>(key))
  52. {
  53. return true;
  54. }
  55. }
  56. return false;
  57. }
  58. #endregion
  59.  
  60. #region 添加缓存
  61. /// <summary>
  62. /// 添加缓存
  63. /// </summary>
  64. public static void Add<T>(string key, object value)
  65. {
  66. Add(typeof(T).Name, key, value);
  67. }
  68. /// <summary>
  69. /// 添加缓存
  70. /// </summary>
  71. public static void Add(Type type, string key, object value)
  72. {
  73. Add(type.Name, key, value);
  74. }
  75. /// <summary>
  76. /// 添加缓存
  77. /// </summary>
  78. public static void Add(string tableName, string key, object value)
  79. {
  80. return; //禁用缓存
  81. if (HttpRuntime.Cache[tableName] == null)
  82. {
  83. Dictionary<string, object> dic = new Dictionary<string, object>();
  84. dic.Add(key, value);
  85. HttpRuntime.Cache.Insert(tableName, dic);
  86. }
  87. else
  88. {
  89. Dictionary<string, object> dic = (Dictionary<string, object>)HttpRuntime.Cache[tableName];
  90. if (dic.Keys.Contains<string>(key))
  91. {
  92. dic[key] = value;
  93. }
  94. else
  95. {
  96. dic.Add(key, value);
  97. }
  98. HttpRuntime.Cache[tableName] = dic;
  99. }
  100. }
  101. #endregion
  102.  
  103. #region 获取缓存
  104. /// <summary>
  105. /// 获取缓存
  106. /// </summary>
  107. public static object Get<T>(string key)
  108. {
  109. return Get(typeof(T).Name, key);
  110. }
  111. /// <summary>
  112. /// 获取缓存
  113. /// </summary>
  114. public static object Get(Type type, string key)
  115. {
  116. return Get(type.Name, key);
  117. }
  118. /// <summary>
  119. /// 获取缓存
  120. /// </summary>
  121. public static object Get(string tableName, string key)
  122. {
  123. return null; //禁用缓存
  124. if (HttpRuntime.Cache[tableName] != null)
  125. {
  126. Dictionary<string, object> dic = (Dictionary<string, object>)HttpRuntime.Cache[tableName];
  127. if (dic.Keys.Contains<string>(key))
  128. {
  129. return dic[key];
  130. }
  131. }
  132. return null;
  133. }
  134. #endregion
  135.  
  136. #region 删除缓存
  137. /// <summary>
  138. /// 删除所有缓存
  139. /// </summary>
  140. public static void Clear()
  141. {
  142. return; //禁用缓存
  143. string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
  144. int start = connectionString.IndexOf("database=") + ;
  145. int end = connectionString.IndexOf("user id=");
  146. string owner = connectionString.Substring(start, end - start).Replace(";", "").ToUpper();
  147. MySqlHelper dbHelper = new MySqlHelper();
  148. DataTable dt = dbHelper.Query(string.Format(@"
  149. SELECT TABLE_NAME as TABLE_NAME,TABLE_COMMENT as COMMENTS
  150. FROM INFORMATION_SCHEMA.TABLES
  151. WHERE TABLE_SCHEMA = '{0}'", owner)).Tables[];
  152. foreach (DataRow dr in dt.Rows)
  153. {
  154. HttpRuntime.Cache.Remove(dr["TABLE_NAME"].ToString());
  155. HttpRuntime.Cache.Remove(dr["TABLE_NAME"].ToString() + "_ext");
  156. }
  157. HttpRuntime.Cache.Remove(pageCacheKey);
  158. }
  159. /// <summary>
  160. /// 删除缓存
  161. /// </summary>
  162. public static void Remove<T>()
  163. {
  164. Remove(typeof(T).Name);
  165. }
  166. /// <summary>
  167. /// 删除缓存
  168. /// </summary>
  169. public static void Remove(Type type)
  170. {
  171. Remove(type.Name);
  172. }
  173. /// <summary>
  174. /// 删除缓存
  175. /// </summary>
  176. public static void Remove(string tableName)
  177. {
  178. return; //禁用缓存
  179. HttpRuntime.Cache.Remove(tableName);
  180. HttpRuntime.Cache.Remove(tableName + "_ext");
  181. HttpRuntime.Cache.Remove(pageCacheKey);
  182. }
  183. #endregion
  184.  
  185. }
  186. }

添加、修改、删除操作十分简捷方便,分别只需要一行代码。在并发量很小的情况下,可以通过GetMaxID方法生产新的ID,否则请采用其它方法。代码如下:

  1. #region 添加
  2. /// <summary>
  3. /// 添加
  4. /// </summary>
  5. public void Insert(cms_content model)
  6. {
  7. model.id = dbHelper.GetMaxID<cms_content>("id");
  8. dbHelper.Insert(model);
  9. }
  10. #endregion
  11.  
  12. #region 修改
  13. /// <summary>
  14. /// 修改
  15. /// </summary>
  16. public void Update(cms_content model)
  17. {
  18. dbHelper.Update(model);
  19. }
  20. #endregion
  21.  
  22. #region 删除
  23. /// <summary>
  24. /// 删除
  25. /// </summary>
  26. public void Del(string ids)
  27. {
  28. dbHelper.BatchDelete<cms_content>(ids);
  29. }
  30. #endregion

查询单个实体也非常方便,可以用ID查询,也可以写原生sql语句查询,十分灵活。代码如下:

  1. /// <summary>
  2. /// 获取
  3. /// </summary>
  4. public cms_content Get(int id)
  5. {
  6. return dbHelper.FindById<cms_content>(id.ToString());
  7. }
  8. /// <summary>
  9. /// 根据channelId获取一条内容详情
  10. /// </summary>
  11. public cms_content GetByChannelId(int channelId)
  12. {
  13. return dbHelper.FindBySql<cms_content>(string.Format("select * from cms_content where channelId={0} and audit=1", channelId));
  14. }

查询获取集合使用原生sql语句,非常灵活方便,你可以写非常非常复杂的sql语句,各种join,各种子查询,都可以。代码如下:

  1. /// <summary>
  2. /// 获取列表
  3. /// </summary>
  4. public List<cms_content_ext> GetList(ref PagerModel pager, int channelId, string title, int audit)
  5. {
  6. StringBuilder sql = new StringBuilder(string.Format(@"
  7. select content.*, channel.title as channelName, user.showName
  8. from cms_content content
  9. left join cms_channel channel on channel.id=content.channelId
  10. left join sys_user user on user.id=content.publishUserId
  11. where 1=1 "));
  12.  
  13. if (channelId != -)
  14. {
  15. sql.AppendFormat(" and content.channelId = {0}", channelId);
  16. }
  17. if (!string.IsNullOrWhiteSpace(title))
  18. {
  19. sql.AppendFormat(" and content.title like '%{0}%'", title);
  20. }
  21. if (audit != -)
  22. {
  23. sql.AppendFormat(" and content.audit = {0}", audit);
  24. }
  25.  
  26. string orderby = string.Format("order by content.publishTime desc,id desc");
  27. PagerModel pagerModel = dbHelper.FindPageBySql<cms_content_ext>(sql.ToString(), orderby, pager.rows, pager.page);
  28. pager.totalRows = pagerModel.totalRows;
  29. pager.result = pagerModel.result;
  30. return pagerModel.result as List<cms_content_ext>;
  31. }

MySqlHelper、CacheHelper的更多相关文章

  1. WebHelper-SessionHelper、CookieHelper、CacheHelper、Tree

    ylbtech-Unitity: cs-WebHelper-SessionHelper.CookieHelper.CacheHelper.Tree SessionHelper.cs CookieHel ...

  2. C# WebHelper-CookieHelper,CacheHelper,SessionHelper

    常用web操作工具类,记录一下,本文记录的工具类,都要求引用 System.Web 1.CookieHelper /// <summary> /// Cookie工具类 /// </ ...

  3. Dos.Common - 目录、介绍

    引言: Dos.Common是一个开发中的常用类库,如HttpHelper.LogHelper.CacheHelper.CookieHelper.MapperHelper等等.与Dos.WeChat. ...

  4. Dos.Common

    引言: Dos.Common是一个开发中的常用类库,如HttpHelper.LogHelper.CacheHelper.CookieHelper.MapperHelper等等.与Dos.WeChat. ...

  5. 话说C#程序员人手一个ORM

    话说C#程序员人手一个ORM,确实没有必要再写ORM了,不过我的ORM并不是新的,是从DBHelper演化过来的,算是DBHelper魔改版. 目前流行的ORM有EF.Dapper.SqlSugar. ...

  6. java操作MySQL数据库(插入、删除、修改、查询、获取所有行数)

    插播一段广告哈:我之前共享了两个自己写的小应用,见这篇博客百度地图开发的两个应用源码共享(Android版),没 想到有人找我来做毕设了,年前交付,时间不是很紧,大概了解了下就接下了,主要用到的就是和 ...

  7. 对依赖倒置原则(DIP)及Ioc、DI、Ioc容器的一些理解

    1.概述 所谓依赖倒置原则(Dependence Inversion Principle)就是要依赖于抽象,不要依赖于具体.简单的说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模 ...

  8. 十二、EnterpriseFrameWork框架核心类库之与EntLib结合

    从本章开始对框架的讲叙开始进入核心类库的讲解,前面都是对框架外在功能讲解,让人有个整体的概念,知道包含哪些功能与对系统开发有什么帮助.以后多章都是讲解核心类库的,讲解的方式基本按照代码的目录结构,这样 ...

  9. PostgreSQL和Greenplum、Npgsql

    PostgreSQL和Greenplum.Npgsql 想着要不要写,两个原因“懒”和“空”.其实懒和空也是有联系的,不是因为懒的写,而是因为对PostgreSQL和Npgsql的知识了解匮乏,也就懒 ...

随机推荐

  1. CSS Font知识整理总结

    1.什么是字体 字体是文字的外在形式,就是文字的风格,是文字的外衣.比如行书.楷书.草书,都是一种字体.同样一个字每个人写起来都会有差异,可以说每个人都有一套潜在的字体库.对于web页面来说,字体就是 ...

  2. [.net 面向对象编程基础] (5) 基础中的基础——变量和常量

    [.net面向对象编程基础]  (5) 基础中的基础——变量和常量 1.常量:在编译时其值能够确定,并且程序运行过程中值不发生变化的量. 通俗来说,就是定义一个不能改变值的量.既然不能变动值,那就必须 ...

  3. http学习笔记(一)

    写在前面: 第一次想写系列文章,学习了一些web知识后,发现自己还有很大的不足,但又不知道该学习些什么来完善自己的知识体系,偶然在网上看到了一篇介绍http的文章,觉得对自己有一些帮助,于是想要开始学 ...

  4. 12小时包你学会基于ReactMix框架的ReactNativeApp开发(二)基于Css+HTML写第一个app页面

    上一篇文章,大家对于ReactMix(https://github.com/xueduany/react-mix)框架有了一个基本认识,知道我们是一个语法糖,帮助大家基于一套代码,所有平台都能跑.那么 ...

  5. 将网站添加到iPhone的主屏幕上

    我之前有篇文章介绍过如何将网站固定到Windows的开始菜单,并可以自定义图标.颜色以及Windows推送通知,其实Apple也有类似的功能,通过在网页的head部分添加link标记,在Safari浏 ...

  6. MySQL 5.7新特性之Generated Column(函数索引)

    MySQL 5.7引入了Generated Column,这篇文章简单地介绍了Generated Column的使用方法和注意事项,为读者了解MySQL 5.7提供一个快速的.完整的教程.这篇文章围绕 ...

  7. JSONP浅析

    DEMO : JSONP示例 为什么使用JSONP JSONP和JSON是不一样的.JSON(JavaScript Object Notation)是一种基于文本的数据交换方式,或者叫做数据描述格式. ...

  8. java基础-继承:矩形体积类问题

    28.按要求编写一个Java应用程序: (1)定义一个类,描述一个矩形,包含有长.宽两种属性,和计算面积方法. (2)编写一个类,继承自矩形类,同时该类描述长方体,具有长.宽.高属性, 和计算体积的方 ...

  9. PHP将富文本编辑后的内容,去除样式图片等只保留txt文本内容

    1.从数据库读取富文本内容样式如下: <p style=";text-indent: 0;padding: 0;line-height: 26px"><span ...

  10. png图片制作任意颜色的小图标

    本内容只要是对张鑫旭PNG格式小图标的CSS任意颜色赋色技术的这篇文章进行详细说明. HTML: <i class="icon"><i class="i ...