支持Oracle、MSSQL、MySQL、SQLite四种数据库,支持事务,支持对象关系映射;已在多个项目中实际使用。

没有语法糖,学习成本几乎为0,拿来即用。

DBHelper类完整代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.Common;
  7. using System.Data.Objects.DataClasses;
  8. using System.Data.OracleClient;
  9. using System.Data.SqlClient;
  10. using System.Data.SQLite;
  11. using System.Reflection;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using MySql.Data.MySqlClient;
  15. using System.Data.OleDb;
  16. using Models;
  17.  
  18. /* ----------------------------------------------------------------------
  19. * 作 者:suxiang
  20. * 创建日期:2016年11月23日
  21. * 更新日期:2020年03月24日
  22. *
  23. * 支持Oracle、MSSQL、MySQL、SQLite、Access数据库
  24. *
  25. * 注意引用的MySql.Data.dll、System.Data.SQLite.dll的版本,32位还是64位
  26. * 有的System.Data.SQLite.dll版本需要依赖SQLite.Interop.dll
  27. *
  28. * 需要配套的PagerModel、IsDBFieldAttribute、IsIdAttribute类
  29. *
  30. * 为方便使用,需要配套的Model生成器
  31. * ---------------------------------------------------------------------- */
  32.  
  33. namespace DBUtil
  34. {
  35. /// <summary>
  36. /// 数据库操作类
  37. /// </summary>
  38. public static class DBHelper
  39. {
  40. #region 变量
  41. /// <summary>
  42. /// 数据库类型
  43. /// </summary>
  44. private static string m_DBType = ConfigurationManager.AppSettings["DBType"];
  45. /// <summary>
  46. /// 数据库类型
  47. /// </summary>
  48. private static bool m_AutoIncrement = ConfigurationManager.AppSettings["AutoIncrement"].ToLower() == "true" ? true : false;
  49. /// <summary>
  50. /// 数据库连接字符串
  51. /// </summary>
  52. private static string m_ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
  53. /// <summary>
  54. /// 事务
  55. /// </summary>
  56. [ThreadStatic]
  57. private static DbTransaction m_Tran;
  58. /// <summary>
  59. /// 带参数的SQL插入和修改语句中,参数前面的符号
  60. /// </summary>
  61. private static string m_ParameterMark = GetParameterMark();
  62. #endregion
  63.  
  64. #region 生成变量
  65. #region 生成 IDbCommand
  66. /// <summary>
  67. /// 生成 IDbCommand
  68. /// </summary>
  69. private static DbCommand GetCommand()
  70. {
  71. DbCommand command = null;
  72.  
  73. switch (m_DBType)
  74. {
  75. case "oracle":
  76. command = new OracleCommand();
  77. break;
  78. case "mssql":
  79. command = new SqlCommand();
  80. break;
  81. case "mysql":
  82. command = new MySqlCommand();
  83. break;
  84. case "sqlite":
  85. command = new SQLiteCommand();
  86. break;
  87. case "access":
  88. command = new OleDbCommand();
  89. break;
  90. }
  91.  
  92. return command;
  93. }
  94. /// <summary>
  95. /// 生成 IDbCommand
  96. /// </summary>
  97. private static DbCommand GetCommand(string sql, DbConnection conn)
  98. {
  99. DbCommand command = null;
  100.  
  101. switch (m_DBType)
  102. {
  103. case "oracle":
  104. command = new OracleCommand(sql);
  105. command.Connection = conn;
  106. break;
  107. case "mssql":
  108. command = new SqlCommand(sql);
  109. command.Connection = conn;
  110. break;
  111. case "mysql":
  112. command = new MySqlCommand(sql);
  113. command.Connection = conn;
  114. break;
  115. case "sqlite":
  116. command = new SQLiteCommand(sql);
  117. command.Connection = conn;
  118. break;
  119. case "access":
  120. command = new OleDbCommand(sql);
  121. command.Connection = conn;
  122. break;
  123. }
  124.  
  125. return command;
  126. }
  127. #endregion
  128.  
  129. #region 生成 IDbConnection
  130. /// <summary>
  131. /// 生成 IDbConnection
  132. /// </summary>
  133. private static DbConnection GetConnection()
  134. {
  135. DbConnection conn = null;
  136.  
  137. switch (m_DBType)
  138. {
  139. case "oracle":
  140. conn = new OracleConnection(m_ConnectionString);
  141. break;
  142. case "mssql":
  143. conn = new SqlConnection(m_ConnectionString);
  144. break;
  145. case "mysql":
  146. conn = new MySqlConnection(m_ConnectionString);
  147. break;
  148. case "sqlite":
  149. conn = new SQLiteConnection(m_ConnectionString);
  150. break;
  151. case "access":
  152. conn = new OleDbConnection(m_ConnectionString);
  153. break;
  154. }
  155.  
  156. return conn;
  157. }
  158. #endregion
  159.  
  160. #region 生成 IDbDataAdapter
  161. /// <summary>
  162. /// 生成 IDbDataAdapter
  163. /// </summary>
  164. private static DbDataAdapter GetDataAdapter(DbCommand cmd)
  165. {
  166. DbDataAdapter dataAdapter = null;
  167.  
  168. switch (m_DBType)
  169. {
  170. case "oracle":
  171. dataAdapter = new OracleDataAdapter();
  172. dataAdapter.SelectCommand = cmd;
  173. break;
  174. case "mssql":
  175. dataAdapter = new SqlDataAdapter();
  176. dataAdapter.SelectCommand = cmd;
  177. break;
  178. case "mysql":
  179. dataAdapter = new MySqlDataAdapter();
  180. dataAdapter.SelectCommand = cmd;
  181. break;
  182. case "sqlite":
  183. dataAdapter = new SQLiteDataAdapter();
  184. dataAdapter.SelectCommand = cmd;
  185. break;
  186. case "access":
  187. dataAdapter = new OleDbDataAdapter();
  188. dataAdapter.SelectCommand = cmd;
  189. break;
  190. }
  191.  
  192. return dataAdapter;
  193. }
  194. #endregion
  195.  
  196. #region 生成 m_ParameterMark
  197. /// <summary>
  198. /// 生成 m_ParameterMark
  199. /// </summary>
  200. private static string GetParameterMark()
  201. {
  202. switch (m_DBType)
  203. {
  204. case "oracle":
  205. return ":";
  206. case "mssql":
  207. return "@";
  208. case "mysql":
  209. return "@";
  210. case "sqlite":
  211. return ":";
  212. case "access":
  213. return "@";
  214. }
  215. return ":";
  216. }
  217. #endregion
  218.  
  219. #region 生成 DbParameter
  220. /// <summary>
  221. /// 生成 DbParameter
  222. /// </summary>
  223. private static DbParameter GetDbParameter(string name, object vallue)
  224. {
  225. DbParameter dbParameter = null;
  226.  
  227. switch (m_DBType)
  228. {
  229. case "oracle":
  230. dbParameter = new OracleParameter(name, vallue);
  231. break;
  232. case "mssql":
  233. dbParameter = new SqlParameter(name, vallue);
  234. break;
  235. case "mysql":
  236. dbParameter = new MySqlParameter(name, vallue);
  237. break;
  238. case "sqlite":
  239. dbParameter = new SQLiteParameter(name, vallue);
  240. break;
  241. case "access":
  242. dbParameter = new OleDbParameter(name, vallue);
  243. break;
  244. }
  245.  
  246. return dbParameter;
  247. }
  248. #endregion
  249. #endregion
  250.  
  251. #region 基础方法
  252. #region 执行简单SQL语句
  253. #region Exists
  254. public static bool Exists(string sqlString)
  255. {
  256. SqlFilter(ref sqlString);
  257. using (DbConnection conn = GetConnection())
  258. {
  259. using (DbCommand cmd = GetCommand(sqlString, conn))
  260. {
  261. try
  262. {
  263. conn.Open();
  264. object obj = cmd.ExecuteScalar();
  265. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  266. {
  267. return false;
  268. }
  269. else
  270. {
  271. return true;
  272. }
  273. }
  274. catch (Exception ex)
  275. {
  276. throw ex;
  277. }
  278. finally
  279. {
  280. cmd.Dispose();
  281. conn.Close();
  282. }
  283. }
  284. }
  285. }
  286. #endregion
  287.  
  288. #region 执行SQL语句,返回影响的记录数
  289. /// <summary>
  290. /// 执行SQL语句,返回影响的记录数
  291. /// </summary>
  292. /// <param name="sqlString">SQL语句</param>
  293. /// <returns>影响的记录数</returns>
  294. public static int ExecuteSql(string sqlString)
  295. {
  296. SqlFilter(ref sqlString);
  297. DbConnection conn = m_Tran == null ? GetConnection() : m_Tran.Connection;
  298. using (DbCommand cmd = GetCommand(sqlString, conn))
  299. {
  300. try
  301. {
  302. if (conn.State != ConnectionState.Open) conn.Open();
  303. if (m_Tran != null) cmd.Transaction = m_Tran;
  304. int rows = cmd.ExecuteNonQuery();
  305. return rows;
  306. }
  307. catch (Exception ex)
  308. {
  309. throw new Exception(ex.Message);
  310. }
  311. finally
  312. {
  313. cmd.Dispose();
  314. if (m_Tran == null) conn.Close();
  315. }
  316. }
  317. }
  318. #endregion
  319.  
  320. #region 执行一条计算查询结果语句,返回查询结果
  321. /// <summary>
  322. /// 执行一条计算查询结果语句,返回查询结果(object)
  323. /// </summary>
  324. /// <param name="sqlString">计算查询结果语句</param>
  325. /// <returns>查询结果(object)</returns>
  326. public static object GetSingle(string sqlString)
  327. {
  328. SqlFilter(ref sqlString);
  329. using (DbConnection conn = GetConnection())
  330. {
  331. using (DbCommand cmd = GetCommand(sqlString, conn))
  332. {
  333. try
  334. {
  335. if (conn.State != ConnectionState.Open) conn.Open();
  336. object obj = cmd.ExecuteScalar();
  337. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  338. {
  339. return null;
  340. }
  341. else
  342. {
  343. return obj;
  344. }
  345. }
  346. catch (Exception ex)
  347. {
  348. throw ex;
  349. }
  350. finally
  351. {
  352. cmd.Dispose();
  353. }
  354. }
  355. }
  356. }
  357. #endregion
  358.  
  359. #region 执行查询语句,返回IDataReader
  360. /// <summary>
  361. /// 执行查询语句,返回IDataReader ( 注意:调用该方法后,一定要对IDataReader进行Close )
  362. /// </summary>
  363. /// <param name="sqlString">查询语句</param>
  364. /// <returns>IDataReader</returns>
  365. public static DbDataReader ExecuteReader(string sqlString)
  366. {
  367. SqlFilter(ref sqlString);
  368. DbConnection conn = GetConnection();
  369. DbCommand cmd = GetCommand(sqlString, conn);
  370. try
  371. {
  372. if (conn.State != ConnectionState.Open) conn.Open();
  373. DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  374. return myReader;
  375. }
  376. catch (Exception ex)
  377. {
  378. throw ex;
  379. }
  380. }
  381. #endregion
  382.  
  383. #region 执行查询语句,返回DataSet
  384. /// <summary>
  385. /// 执行查询语句,返回DataSet
  386. /// </summary>
  387. /// <param name="sqlString">查询语句</param>
  388. /// <returns>DataSet</returns>
  389. public static DataSet Query(string sqlString)
  390. {
  391. SqlFilter(ref sqlString);
  392. using (DbConnection conn = GetConnection())
  393. {
  394. DataSet ds = new DataSet();
  395. try
  396. {
  397. conn.Open();
  398. using (DbCommand cmd = GetCommand(sqlString, conn))
  399. {
  400. DbDataAdapter adapter = GetDataAdapter(cmd);
  401. adapter.Fill(ds, "ds");
  402. }
  403. }
  404. catch (Exception ex)
  405. {
  406. throw ex;
  407. }
  408. finally
  409. {
  410. conn.Close();
  411. }
  412. return ds;
  413. }
  414. }
  415. #endregion
  416.  
  417. #region SQL过滤,防注入
  418. /// <summary>
  419. /// SQL过滤,防注入
  420. /// </summary>
  421. /// <param name="sql">sql</param>
  422. public static void SqlFilter(ref string sql)
  423. {
  424. sql = sql.Trim();
  425. List<string> keywordList = new List<string>() {
  426. "net localgroup ",
  427. "net user ",
  428. "xp_cmdshell ",
  429. "exec ",
  430. "execute ",
  431. "truncate ",
  432. "drop ",
  433. "restore ",
  434. "create ",
  435. "alter ",
  436. "rename ",
  437. "insert ",
  438. "update ",
  439. "delete ",
  440. "select "};
  441. string ignore = string.Empty;
  442. string upperSql = sql.ToUpper();
  443. foreach (string keyword in keywordList)
  444. {
  445. if (upperSql.IndexOf(keyword.ToUpper()) == )
  446. {
  447. ignore = keyword;
  448. }
  449. }
  450. foreach (string keyword in keywordList)
  451. {
  452. if (ignore == "select " && ignore == keyword) continue;
  453. Regex regex = new Regex(keyword.Replace(" ", "[\\s]+"), RegexOptions.IgnoreCase);
  454. sql = sql.Substring(, ignore.Length) + regex.Replace(sql.Substring(ignore.Length), string.Empty);
  455. }
  456. }
  457. #endregion
  458. #endregion
  459.  
  460. #region 执行带参数的SQL语句
  461. #region 执行SQL语句,返回影响的记录数
  462. /// <summary>
  463. /// 执行SQL语句,返回影响的记录数
  464. /// </summary>
  465. /// <param name="SQLString">SQL语句</param>
  466. /// <returns>影响的记录数</returns>
  467. public static int ExecuteSql(string SQLString, params DbParameter[] cmdParms)
  468. {
  469. DbConnection conn = m_Tran == null ? GetConnection() : m_Tran.Connection;
  470. using (DbCommand cmd = GetCommand())
  471. {
  472. try
  473. {
  474. PrepareCommand(cmd, conn, m_Tran, SQLString, cmdParms);
  475. int rows = cmd.ExecuteNonQuery();
  476. cmd.Parameters.Clear();
  477. return rows;
  478. }
  479. catch (Exception ex)
  480. {
  481. throw ex;
  482. }
  483. finally
  484. {
  485. cmd.Dispose();
  486. if (m_Tran == null) conn.Close();
  487. }
  488. }
  489. }
  490. #endregion
  491.  
  492. #region 执行查询语句,返回IDataReader
  493. /// <summary>
  494. /// 执行查询语句,返回IDataReader ( 注意:调用该方法后,一定要对IDataReader进行Close )
  495. /// </summary>
  496. /// <param name="strSQL">查询语句</param>
  497. /// <returns>IDataReader</returns>
  498. public static DbDataReader ExecuteReader(string sqlString, params DbParameter[] cmdParms)
  499. {
  500. DbConnection conn = GetConnection();
  501. DbCommand cmd = GetCommand();
  502. try
  503. {
  504. PrepareCommand(cmd, conn, null, sqlString, cmdParms);
  505. DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  506. cmd.Parameters.Clear();
  507. return myReader;
  508. }
  509. catch (Exception ex)
  510. {
  511. throw ex;
  512. }
  513.  
  514. }
  515. #endregion
  516.  
  517. #region 执行查询语句,返回DataSet
  518. /// <summary>
  519. /// 执行查询语句,返回DataSet
  520. /// </summary>
  521. /// <param name="sqlString">查询语句</param>
  522. /// <returns>DataSet</returns>
  523. public static DataSet Query(string sqlString, params DbParameter[] cmdParms)
  524. {
  525. DbConnection conn = GetConnection();
  526. DbCommand cmd = GetCommand();
  527. PrepareCommand(cmd, conn, null, sqlString, cmdParms);
  528. using (DbDataAdapter da = GetDataAdapter(cmd))
  529. {
  530. DataSet ds = new DataSet();
  531. try
  532. {
  533. da.Fill(ds, "ds");
  534. cmd.Parameters.Clear();
  535. }
  536. catch (Exception ex)
  537. {
  538. throw ex;
  539. }
  540. finally
  541. {
  542. cmd.Dispose();
  543. conn.Close();
  544. }
  545. return ds;
  546. }
  547. }
  548. #endregion
  549.  
  550. #region PrepareCommand
  551. private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms)
  552. {
  553. if (conn.State != ConnectionState.Open) conn.Open();
  554. cmd.Connection = conn;
  555. cmd.CommandText = cmdText;
  556. if (trans != null) cmd.Transaction = trans;
  557. cmd.CommandType = CommandType.Text;
  558. if (cmdParms != null)
  559. {
  560. foreach (DbParameter parm in cmdParms)
  561. {
  562. cmd.Parameters.Add(parm);
  563. }
  564. }
  565. }
  566. #endregion
  567. #endregion
  568. #endregion
  569.  
  570. #region 增删改查
  571. #region 获取最大编号
  572. /// <summary>
  573. /// 获取最大编号
  574. /// </summary>
  575. /// <typeparam name="T">实体Model</typeparam>
  576. /// <param name="key">主键</param>
  577. public static int GetMaxID<T>(string key)
  578. {
  579. Type type = typeof(T);
  580.  
  581. string sql = null;
  582. switch (m_DBType)
  583. {
  584. case "oracle":
  585. sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
  586. break;
  587. case "mssql":
  588. sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
  589. break;
  590. case "mysql":
  591. sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
  592. break;
  593. case "sqlite":
  594. sql = string.Format("SELECT Max(cast({0} as int)) FROM {1}", key, type.Name);
  595. break;
  596. case "access":
  597. sql = string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
  598. break;
  599. }
  600.  
  601. using (DbConnection conn = GetConnection())
  602. {
  603. using (IDbCommand cmd = GetCommand(sql, conn))
  604. {
  605. try
  606. {
  607. conn.Open();
  608. object obj = cmd.ExecuteScalar();
  609. if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
  610. {
  611. return ;
  612. }
  613. else
  614. {
  615. return int.Parse(obj.ToString()) + ;
  616. }
  617. }
  618. catch (Exception ex)
  619. {
  620. throw ex;
  621. }
  622. finally
  623. {
  624. cmd.Dispose();
  625. conn.Close();
  626. }
  627. }
  628. }
  629. }
  630. #endregion
  631.  
  632. #region 添加
  633. /// <summary>
  634. /// 添加
  635. /// </summary>
  636. public static void Insert(object obj)
  637. {
  638. Insert(obj, m_AutoIncrement);
  639. }
  640. /// <summary>
  641. /// 添加
  642. /// </summary>
  643. public static void Insert(object obj, bool autoIncrement)
  644. {
  645. StringBuilder strSql = new StringBuilder();
  646. Type type = obj.GetType();
  647. strSql.Append(string.Format("insert into {0}(", type.Name));
  648.  
  649. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  650. List<string> propertyNameList = new List<string>();
  651. int savedCount = ;
  652. foreach (PropertyInfo propertyInfo in propertyInfoList)
  653. {
  654. if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > && autoIncrement) continue;
  655. if (propertyInfo.GetCustomAttributes(typeof(IsDBFieldAttribute), false).Length > )
  656. {
  657. propertyNameList.Add(propertyInfo.Name);
  658. savedCount++;
  659. }
  660. }
  661.  
  662. strSql.Append(string.Format("{0})", string.Join(",", propertyNameList.ToArray())));
  663. strSql.Append(string.Format(" values ({0})", string.Join(",", propertyNameList.ConvertAll<string>(a => m_ParameterMark + a).ToArray())));
  664. DbParameter[] parameters = new DbParameter[savedCount];
  665. int k = ;
  666. for (int i = ; i < propertyInfoList.Length && savedCount > ; i++)
  667. {
  668. PropertyInfo propertyInfo = propertyInfoList[i];
  669. if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > && autoIncrement) continue;
  670. if (propertyInfo.GetCustomAttributes(typeof(IsDBFieldAttribute), false).Length > )
  671. {
  672. object val = propertyInfo.GetValue(obj, null);
  673. DbParameter param = GetDbParameter(m_ParameterMark + propertyInfo.Name, val == null ? DBNull.Value : val);
  674. parameters[k++] = param;
  675. }
  676. }
  677.  
  678. ExecuteSql(strSql.ToString(), parameters);
  679. }
  680. #endregion
  681.  
  682. #region 修改
  683. /// <summary>
  684. /// 修改
  685. /// </summary>
  686. public static void Update(object obj)
  687. {
  688. object oldObj = Find(obj, false);
  689. if (oldObj == null) throw new Exception("无法获取到旧数据");
  690.  
  691. StringBuilder strSql = new StringBuilder();
  692. Type type = obj.GetType();
  693. strSql.Append(string.Format("update {0} ", type.Name));
  694.  
  695. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  696. List<string> propertyNameList = new List<string>();
  697. int savedCount = ;
  698. foreach (PropertyInfo propertyInfo in propertyInfoList)
  699. {
  700. if (propertyInfo.GetCustomAttributes(typeof(IsDBFieldAttribute), false).Length > )
  701. {
  702. object oldVal = propertyInfo.GetValue(oldObj, null);
  703. object val = propertyInfo.GetValue(obj, null);
  704. if (!object.Equals(oldVal, val))
  705. {
  706. propertyNameList.Add(propertyInfo.Name);
  707. savedCount++;
  708. }
  709. }
  710. }
  711.  
  712. strSql.Append(string.Format(" set "));
  713. DbParameter[] parameters = new DbParameter[savedCount];
  714. StringBuilder sbPros = new StringBuilder();
  715. int k = ;
  716. for (int i = ; i < propertyInfoList.Length && savedCount > ; i++)
  717. {
  718. PropertyInfo propertyInfo = propertyInfoList[i];
  719. if (propertyInfo.GetCustomAttributes(typeof(IsDBFieldAttribute), false).Length > )
  720. {
  721. object oldVal = propertyInfo.GetValue(oldObj, null);
  722. object val = propertyInfo.GetValue(obj, null);
  723. if (!object.Equals(oldVal, val))
  724. {
  725. sbPros.Append(string.Format(" {0}={1}{0},", propertyInfo.Name, m_ParameterMark));
  726. DbParameter param = GetDbParameter(m_ParameterMark + propertyInfo.Name, val == null ? DBNull.Value : val);
  727. parameters[k++] = param;
  728. }
  729. }
  730. }
  731. if (sbPros.Length > )
  732. {
  733. strSql.Append(sbPros.ToString(, sbPros.Length - ));
  734. }
  735. strSql.Append(string.Format(" where {0}='{1}'", GetIdName(obj.GetType()), GetIdVal(obj).ToString()));
  736.  
  737. if (savedCount > )
  738. {
  739. ExecuteSql(strSql.ToString(), parameters);
  740. }
  741. }
  742. #endregion
  743.  
  744. #region 删除
  745. /// <summary>
  746. /// 根据Id删除
  747. /// </summary>
  748. public static void Delete<T>(int id)
  749. {
  750. Type type = typeof(T);
  751. StringBuilder sbSql = new StringBuilder();
  752. DbParameter[] cmdParms = new DbParameter[];
  753. cmdParms[] = GetDbParameter(m_ParameterMark + GetIdName(type), id);
  754. sbSql.Append(string.Format("delete from {0} where {2}={1}{2}", type.Name, m_ParameterMark, GetIdName(type)));
  755.  
  756. ExecuteSql(sbSql.ToString(), cmdParms);
  757. }
  758. /// <summary>
  759. /// 根据Id集合删除
  760. /// </summary>
  761. public static void BatchDelete<T>(string ids)
  762. {
  763. if (string.IsNullOrWhiteSpace(ids)) return;
  764.  
  765. Type type = typeof(T);
  766. StringBuilder sbSql = new StringBuilder();
  767. string[] idArr = ids.Split(',');
  768. DbParameter[] cmdParms = new DbParameter[idArr.Length];
  769. sbSql.AppendFormat("delete from {0} where {1} in (", type.Name, GetIdName(type));
  770. for (int i = ; i < idArr.Length; i++)
  771. {
  772. cmdParms[i] = GetDbParameter(m_ParameterMark + GetIdName(type) + i, idArr[i]);
  773. sbSql.AppendFormat("{1}{2}{3},", type.Name, m_ParameterMark, GetIdName(type), i);
  774. }
  775. sbSql.Remove(sbSql.Length - , );
  776. sbSql.Append(")");
  777.  
  778. ExecuteSql(sbSql.ToString(), cmdParms);
  779. }
  780. /// <summary>
  781. /// 根据条件删除
  782. /// </summary>
  783. public static void Delete<T>(string conditions)
  784. {
  785. if (string.IsNullOrWhiteSpace(conditions)) return;
  786.  
  787. Type type = typeof(T);
  788. StringBuilder sbSql = new StringBuilder();
  789. SqlFilter(ref conditions);
  790. sbSql.Append(string.Format("delete from {0} where {1}", type.Name, conditions));
  791.  
  792. ExecuteSql(sbSql.ToString());
  793. }
  794. #endregion
  795.  
  796. #region 获取实体
  797. #region 根据实体获取实体
  798. /// <summary>
  799. /// 根据实体获取实体
  800. /// </summary>
  801. private static object Find(object obj, bool readCache = true)
  802. {
  803. Type type = obj.GetType();
  804.  
  805. object result = Activator.CreateInstance(type);
  806. bool hasValue = false;
  807. IDataReader rd = null;
  808.  
  809. string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, GetIdVal(obj), GetIdName(obj.GetType()));
  810.  
  811. try
  812. {
  813. rd = ExecuteReader(sql);
  814.  
  815. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  816.  
  817. int fcnt = rd.FieldCount;
  818. List<string> fileds = new List<string>();
  819. for (int i = ; i < fcnt; i++)
  820. {
  821. fileds.Add(rd.GetName(i).ToUpper());
  822. }
  823.  
  824. while (rd.Read())
  825. {
  826. hasValue = true;
  827. IDataRecord record = rd;
  828.  
  829. foreach (PropertyInfo pro in propertyInfoList)
  830. {
  831. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  832. {
  833. continue;
  834. }
  835.  
  836. pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  837. }
  838. }
  839. }
  840. catch (Exception ex)
  841. {
  842. throw ex;
  843. }
  844. finally
  845. {
  846. if (rd != null && !rd.IsClosed)
  847. {
  848. rd.Close();
  849. rd.Dispose();
  850. }
  851. }
  852.  
  853. if (hasValue)
  854. {
  855. return result;
  856. }
  857. else
  858. {
  859. return null;
  860. }
  861. }
  862. #endregion
  863.  
  864. #region 根据Id获取实体
  865. /// <summary>
  866. /// 根据Id获取实体
  867. /// </summary>
  868. private static object FindById(Type type, int id)
  869. {
  870. object result = Activator.CreateInstance(type);
  871. IDataReader rd = null;
  872. bool hasValue = false;
  873.  
  874. string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));
  875.  
  876. try
  877. {
  878. rd = ExecuteReader(sql);
  879.  
  880. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  881.  
  882. int fcnt = rd.FieldCount;
  883. List<string> fileds = new List<string>();
  884. for (int i = ; i < fcnt; i++)
  885. {
  886. fileds.Add(rd.GetName(i).ToUpper());
  887. }
  888.  
  889. while (rd.Read())
  890. {
  891. hasValue = true;
  892. IDataRecord record = rd;
  893.  
  894. foreach (PropertyInfo pro in propertyInfoList)
  895. {
  896. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  897. {
  898. continue;
  899. }
  900.  
  901. pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  902. }
  903. }
  904. }
  905. catch (Exception ex)
  906. {
  907. throw ex;
  908. }
  909. finally
  910. {
  911. if (rd != null && !rd.IsClosed)
  912. {
  913. rd.Close();
  914. rd.Dispose();
  915. }
  916. }
  917.  
  918. if (hasValue)
  919. {
  920. return result;
  921. }
  922. else
  923. {
  924. return null;
  925. }
  926. }
  927. #endregion
  928.  
  929. #region 根据Id获取实体
  930. /// <summary>
  931. /// 根据Id获取实体
  932. /// </summary>
  933. public static T FindById<T>(string id) where T : new()
  934. {
  935. Type type = typeof(T);
  936. T result = (T)Activator.CreateInstance(type);
  937. IDataReader rd = null;
  938. bool hasValue = false;
  939.  
  940. string sql = string.Format("select * from {0} where {2}='{1}'", type.Name, id, GetIdName(type));
  941.  
  942. try
  943. {
  944. rd = ExecuteReader(sql);
  945.  
  946. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  947.  
  948. int fcnt = rd.FieldCount;
  949. List<string> fileds = new List<string>();
  950. for (int i = ; i < fcnt; i++)
  951. {
  952. fileds.Add(rd.GetName(i).ToUpper());
  953. }
  954.  
  955. while (rd.Read())
  956. {
  957. hasValue = true;
  958. IDataRecord record = rd;
  959.  
  960. foreach (PropertyInfo pro in propertyInfoList)
  961. {
  962. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  963. {
  964. continue;
  965. }
  966.  
  967. pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  968. }
  969. }
  970. }
  971. catch (Exception ex)
  972. {
  973. throw ex;
  974. }
  975. finally
  976. {
  977. if (rd != null && !rd.IsClosed)
  978. {
  979. rd.Close();
  980. rd.Dispose();
  981. }
  982. }
  983.  
  984. if (hasValue)
  985. {
  986. return result;
  987. }
  988. else
  989. {
  990. return default(T);
  991. }
  992. }
  993. #endregion
  994.  
  995. #region 根据sql获取实体
  996. /// <summary>
  997. /// 根据sql获取实体
  998. /// </summary>
  999. public static T FindBySql<T>(string sql) where T : new()
  1000. {
  1001. Type type = typeof(T);
  1002. T result = (T)Activator.CreateInstance(type);
  1003. IDataReader rd = null;
  1004. bool hasValue = false;
  1005.  
  1006. try
  1007. {
  1008. rd = ExecuteReader(sql);
  1009.  
  1010. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  1011.  
  1012. int fcnt = rd.FieldCount;
  1013. List<string> fileds = new List<string>();
  1014. for (int i = ; i < fcnt; i++)
  1015. {
  1016. fileds.Add(rd.GetName(i).ToUpper());
  1017. }
  1018.  
  1019. while (rd.Read())
  1020. {
  1021. hasValue = true;
  1022. IDataRecord record = rd;
  1023.  
  1024. foreach (PropertyInfo pro in propertyInfoList)
  1025. {
  1026. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  1027. {
  1028. continue;
  1029. }
  1030.  
  1031. pro.SetValue(result, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  1032. }
  1033. }
  1034. }
  1035. catch (Exception ex)
  1036. {
  1037. throw ex;
  1038. }
  1039. finally
  1040. {
  1041. if (rd != null && !rd.IsClosed)
  1042. {
  1043. rd.Close();
  1044. rd.Dispose();
  1045. }
  1046. }
  1047.  
  1048. if (hasValue)
  1049. {
  1050. return result;
  1051. }
  1052. else
  1053. {
  1054. return default(T);
  1055. }
  1056. }
  1057. #endregion
  1058. #endregion
  1059.  
  1060. #region 获取列表
  1061. /// <summary>
  1062. /// 获取列表
  1063. /// </summary>
  1064. public static List<T> FindListBySql<T>(string sql) where T : new()
  1065. {
  1066. List<T> list = new List<T>();
  1067. object obj;
  1068. IDataReader rd = null;
  1069.  
  1070. try
  1071. {
  1072. rd = ExecuteReader(sql);
  1073.  
  1074. if (typeof(T) == typeof(int))
  1075. {
  1076. while (rd.Read())
  1077. {
  1078. list.Add((T)rd[]);
  1079. }
  1080. }
  1081. else if (typeof(T) == typeof(string))
  1082. {
  1083. while (rd.Read())
  1084. {
  1085. list.Add((T)rd[]);
  1086. }
  1087. }
  1088. else
  1089. {
  1090. PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();
  1091.  
  1092. int fcnt = rd.FieldCount;
  1093. List<string> fileds = new List<string>();
  1094. for (int i = ; i < fcnt; i++)
  1095. {
  1096. fileds.Add(rd.GetName(i).ToUpper());
  1097. }
  1098.  
  1099. while (rd.Read())
  1100. {
  1101. IDataRecord record = rd;
  1102. obj = new T();
  1103.  
  1104. foreach (PropertyInfo pro in propertyInfoList)
  1105. {
  1106. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  1107. {
  1108. continue;
  1109. }
  1110.  
  1111. pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  1112. }
  1113. list.Add((T)obj);
  1114. }
  1115. }
  1116. }
  1117. catch (Exception ex)
  1118. {
  1119. throw ex;
  1120. }
  1121. finally
  1122. {
  1123. if (rd != null && !rd.IsClosed)
  1124. {
  1125. rd.Close();
  1126. rd.Dispose();
  1127. }
  1128. }
  1129.  
  1130. return list;
  1131. }
  1132. #endregion
  1133.  
  1134. #region 获取列表
  1135. /// <summary>
  1136. /// 获取列表
  1137. /// </summary>
  1138. public static List<T> FindListBySql<T>(string sql, params DbParameter[] cmdParms) where T : new()
  1139. {
  1140. List<T> list = new List<T>();
  1141. object obj;
  1142. IDataReader rd = null;
  1143.  
  1144. try
  1145. {
  1146. rd = ExecuteReader(sql, cmdParms);
  1147.  
  1148. if (typeof(T) == typeof(int))
  1149. {
  1150. while (rd.Read())
  1151. {
  1152. list.Add((T)rd[]);
  1153. }
  1154. }
  1155. else if (typeof(T) == typeof(string))
  1156. {
  1157. while (rd.Read())
  1158. {
  1159. list.Add((T)rd[]);
  1160. }
  1161. }
  1162. else
  1163. {
  1164. PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();
  1165.  
  1166. int fcnt = rd.FieldCount;
  1167. List<string> fileds = new List<string>();
  1168. for (int i = ; i < fcnt; i++)
  1169. {
  1170. fileds.Add(rd.GetName(i).ToUpper());
  1171. }
  1172.  
  1173. while (rd.Read())
  1174. {
  1175. IDataRecord record = rd;
  1176. obj = new T();
  1177.  
  1178. foreach (PropertyInfo pro in propertyInfoList)
  1179. {
  1180. if (!fileds.Contains(pro.Name.ToUpper()) || record[pro.Name] == DBNull.Value)
  1181. {
  1182. continue;
  1183. }
  1184.  
  1185. pro.SetValue(obj, record[pro.Name] == DBNull.Value ? null : getReaderValue(record[pro.Name], pro.PropertyType), null);
  1186. }
  1187. list.Add((T)obj);
  1188. }
  1189. }
  1190. }
  1191. catch (Exception ex)
  1192. {
  1193. throw ex;
  1194. }
  1195. finally
  1196. {
  1197. if (rd != null && !rd.IsClosed)
  1198. {
  1199. rd.Close();
  1200. rd.Dispose();
  1201. }
  1202. }
  1203.  
  1204. return list;
  1205. }
  1206. #endregion
  1207.  
  1208. #region 分页获取列表
  1209. /// <summary>
  1210. /// 分页(任意entity,尽量少的字段)
  1211. /// </summary>
  1212. public static PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage) where T : new()
  1213. {
  1214. PagerModel pagerModel = new PagerModel(currentPage, pageSize);
  1215.  
  1216. using (DbConnection connection = GetConnection())
  1217. {
  1218. connection.Open();
  1219. IDbCommand cmd = null;
  1220. StringBuilder sb = new StringBuilder();
  1221. string commandText = null;
  1222. int startRow = ;
  1223. int endRow = ;
  1224. switch (m_DBType)
  1225. {
  1226. case "oracle":
  1227. #region 分页查询语句
  1228. commandText = string.Format("select count(*) from ({0}) T", sql);
  1229. cmd = GetCommand(commandText, connection);
  1230. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1231.  
  1232. startRow = pageSize * (currentPage - );
  1233. endRow = startRow + pageSize;
  1234.  
  1235. sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
  1236. sb.Append(sql);
  1237. if (!string.IsNullOrWhiteSpace(orderby))
  1238. {
  1239. sb.Append(" ");
  1240. sb.Append(orderby);
  1241. }
  1242. sb.Append(" ) row_limit where rownum <= ");
  1243. sb.Append(endRow);
  1244. sb.Append(" ) where rownum_ >");
  1245. sb.Append(startRow);
  1246. #endregion
  1247. break;
  1248. case "mssql":
  1249. #region 分页查询语句
  1250. commandText = string.Format("select count(*) from ({0}) T", sql);
  1251. cmd = GetCommand(commandText, connection);
  1252. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1253.  
  1254. startRow = pageSize * (currentPage - ) + ;
  1255. endRow = startRow + pageSize - ;
  1256.  
  1257. sb.Append(string.Format(@"
  1258. select * from
  1259. (select ROW_NUMBER() over({1}) as rowNumber, t.* from ({0}) t) tempTable
  1260. where rowNumber between {2} and {3} ", sql, orderby, startRow, endRow));
  1261. #endregion
  1262. break;
  1263. case "mysql":
  1264. #region 分页查询语句
  1265. commandText = string.Format("select count(*) from ({0}) T", sql);
  1266. cmd = GetCommand(commandText, connection);
  1267. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1268.  
  1269. startRow = pageSize * (currentPage - );
  1270.  
  1271. sb.Append("select * from (");
  1272. sb.Append(sql);
  1273. if (!string.IsNullOrWhiteSpace(orderby))
  1274. {
  1275. sb.Append(" ");
  1276. sb.Append(orderby);
  1277. }
  1278. sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
  1279. #endregion
  1280. break;
  1281. case "sqlite":
  1282. #region 分页查询语句
  1283. commandText = string.Format("select count(*) from ({0}) T", sql);
  1284. cmd = GetCommand(commandText, connection);
  1285. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1286.  
  1287. startRow = pageSize * (currentPage - );
  1288.  
  1289. sb.Append(sql);
  1290. if (!string.IsNullOrWhiteSpace(orderby))
  1291. {
  1292. sb.Append(" ");
  1293. sb.Append(orderby);
  1294. }
  1295. sb.AppendFormat(" limit {0} offset {1}", pageSize, startRow);
  1296. #endregion
  1297. break;
  1298. case "access":
  1299. #region 分页查询语句
  1300. commandText = string.Format("select count(*) from ({0}) T", sql);
  1301. cmd = GetCommand(commandText, connection);
  1302. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1303.  
  1304. endRow = pageSize * currentPage;
  1305. startRow = pageSize * currentPage > pagerModel.totalRows ? pagerModel.totalRows - pageSize * (currentPage - ) : pageSize;
  1306. if (startRow <= ) { pagerModel.result = new List<T>(); return pagerModel; }
  1307. string[] orderbyArr = string.Format("{0} asc", orderby.Trim()).Split(' ');
  1308.  
  1309. sb.AppendFormat(@"
  1310. select * from(
  1311. select top {4} * from
  1312. (select top {3} * from ({0}) order by {1} asc)
  1313. order by {1} desc
  1314. ) order by {1} {2}", sql, orderbyArr[], orderbyArr[], endRow, startRow);
  1315. #endregion
  1316. break;
  1317. }
  1318.  
  1319. List<T> list = FindListBySql<T>(sb.ToString());
  1320. pagerModel.result = list;
  1321. }
  1322.  
  1323. return pagerModel;
  1324. }
  1325. #endregion
  1326.  
  1327. #region 分页获取列表
  1328. /// <summary>
  1329. /// 分页(任意entity,尽量少的字段)
  1330. /// </summary>
  1331. /// <typeparam name="T"></typeparam>
  1332. /// <param name="sql"></param>
  1333. /// <returns></returns>
  1334. public static PagerModel FindPageBySql<T>(string sql, string orderby, int pageSize, int currentPage, params DbParameter[] cmdParms) where T : new()
  1335. {
  1336. PagerModel pagerModel = new PagerModel(currentPage, pageSize);
  1337.  
  1338. using (DbConnection connection = GetConnection())
  1339. {
  1340. connection.Open();
  1341. IDbCommand cmd = null;
  1342. StringBuilder sb = new StringBuilder();
  1343. string commandText = null;
  1344. int startRow = ;
  1345. int endRow = ;
  1346. switch (m_DBType)
  1347. {
  1348. case "oracle":
  1349. #region 分页查询语句
  1350. commandText = string.Format("select count(*) from ({0}) T", sql);
  1351. cmd = GetCommand(commandText, connection);
  1352. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1353. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1354.  
  1355. startRow = pageSize * (currentPage - );
  1356. endRow = startRow + pageSize;
  1357.  
  1358. sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
  1359. sb.Append(sql);
  1360. if (!string.IsNullOrWhiteSpace(orderby))
  1361. {
  1362. sb.Append(" ");
  1363. sb.Append(orderby);
  1364. }
  1365. sb.Append(" ) row_limit where rownum <= ");
  1366. sb.Append(endRow);
  1367. sb.Append(" ) where rownum_ >");
  1368. sb.Append(startRow);
  1369. #endregion
  1370. break;
  1371. case "mssql":
  1372. #region 分页查询语句
  1373. commandText = string.Format("select count(*) from ({0}) T", sql);
  1374. cmd = GetCommand(commandText, connection);
  1375. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1376. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1377.  
  1378. startRow = pageSize * (currentPage - ) + ;
  1379. endRow = startRow + pageSize - ;
  1380.  
  1381. sb.Append(string.Format(@"
  1382. select * from
  1383. (select ROW_NUMBER() over({1}) as rowNumber, t.* from ({0}) t) tempTable
  1384. where rowNumber between {2} and {3} ", sql, orderby, startRow, endRow));
  1385. #endregion
  1386. break;
  1387. case "mysql":
  1388. #region 分页查询语句
  1389. commandText = string.Format("select count(*) from ({0}) T", sql);
  1390. cmd = GetCommand(commandText, connection);
  1391. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1392. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1393.  
  1394. startRow = pageSize * (currentPage - );
  1395.  
  1396. sb.Append("select * from (");
  1397. sb.Append(sql);
  1398. if (!string.IsNullOrWhiteSpace(orderby))
  1399. {
  1400. sb.Append(" ");
  1401. sb.Append(orderby);
  1402. }
  1403. sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
  1404. #endregion
  1405. break;
  1406. case "sqlite":
  1407. #region 分页查询语句
  1408. commandText = string.Format("select count(*) from ({0}) T", sql);
  1409. cmd = GetCommand(commandText, connection);
  1410. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1411. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1412.  
  1413. startRow = pageSize * (currentPage - );
  1414.  
  1415. sb.Append(sql);
  1416. if (!string.IsNullOrWhiteSpace(orderby))
  1417. {
  1418. sb.Append(" ");
  1419. sb.Append(orderby);
  1420. }
  1421. sb.AppendFormat(" limit {0} offset {1}", pageSize, startRow);
  1422. #endregion
  1423. break;
  1424. case "access":
  1425. #region 分页查询语句
  1426. commandText = string.Format("select count(*) from ({0}) T", sql);
  1427. cmd = GetCommand(commandText, connection);
  1428. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1429. pagerModel.totalRows = int.Parse(cmd.ExecuteScalar().ToString());
  1430. cmd.Parameters.Clear();
  1431.  
  1432. endRow = pageSize * currentPage;
  1433. startRow = pageSize * currentPage > pagerModel.totalRows ? pagerModel.totalRows - pageSize * (currentPage - ) : pageSize;
  1434. if (startRow <= ) { pagerModel.result = new List<T>(); return pagerModel; }
  1435. string[] orderbyArr = string.Format("{0} asc", orderby.Trim()).Split(' ');
  1436.  
  1437. sb.AppendFormat(@"
  1438. select * from(
  1439. select top {4} * from
  1440. (select top {3} * from ({0}) order by {1} asc)
  1441. order by {1} desc
  1442. ) order by {1} {2}", sql, orderbyArr[], orderbyArr[], endRow, startRow);
  1443. #endregion
  1444. break;
  1445. }
  1446.  
  1447. List<T> list = FindListBySql<T>(sb.ToString(), cmdParms);
  1448. pagerModel.result = list;
  1449. }
  1450.  
  1451. return pagerModel;
  1452. }
  1453.  
  1454. #endregion
  1455.  
  1456. #region 分页获取列表
  1457. /// <summary>
  1458. /// 分页(任意entity,尽量少的字段)
  1459. /// </summary>
  1460. public static DataSet FindPageBySql(string sql, string orderby, int pageSize, int currentPage, out int totalCount, params DbParameter[] cmdParms)
  1461. {
  1462. DataSet ds = null;
  1463.  
  1464. using (DbConnection connection = GetConnection())
  1465. {
  1466. connection.Open();
  1467. IDbCommand cmd = null;
  1468. StringBuilder sb = new StringBuilder();
  1469. string commandText = null;
  1470. int startRow = ;
  1471. int endRow = ;
  1472. totalCount = ;
  1473. switch (m_DBType)
  1474. {
  1475. case "oracle":
  1476. #region 分页查询语句
  1477. commandText = string.Format("select count(*) from ({0}) T", sql);
  1478. cmd = GetCommand(commandText, connection);
  1479. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1480. totalCount = int.Parse(cmd.ExecuteScalar().ToString());
  1481.  
  1482. startRow = pageSize * (currentPage - );
  1483. endRow = startRow + pageSize;
  1484.  
  1485. sb.Append("select * from ( select row_limit.*, rownum rownum_ from (");
  1486. sb.Append(sql);
  1487. if (!string.IsNullOrWhiteSpace(orderby))
  1488. {
  1489. sb.Append(" ");
  1490. sb.Append(orderby);
  1491. }
  1492. sb.Append(" ) row_limit where rownum <= ");
  1493. sb.Append(endRow);
  1494. sb.Append(" ) where rownum_ >");
  1495. sb.Append(startRow);
  1496. #endregion
  1497. break;
  1498. case "mssql":
  1499. #region 分页查询语句
  1500. commandText = string.Format("select count(*) from ({0}) T", sql);
  1501. cmd = GetCommand(commandText, connection);
  1502. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1503. totalCount = int.Parse(cmd.ExecuteScalar().ToString());
  1504.  
  1505. startRow = pageSize * (currentPage - ) + ;
  1506. endRow = startRow + pageSize - ;
  1507.  
  1508. sb.Append(string.Format(@"
  1509. select * from
  1510. (select ROW_NUMBER() over({1}) as rowNumber, t.* from ({0}) t) tempTable
  1511. where rowNumber between {2} and {3} ", sql, orderby, startRow, endRow));
  1512. #endregion
  1513. break;
  1514. case "mysql":
  1515. #region 分页查询语句
  1516. commandText = string.Format("select count(*) from ({0}) T", sql);
  1517. cmd = GetCommand(commandText, connection);
  1518. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1519. totalCount = int.Parse(cmd.ExecuteScalar().ToString());
  1520.  
  1521. startRow = pageSize * (currentPage - );
  1522.  
  1523. sb.Append("select * from (");
  1524. sb.Append(sql);
  1525. if (!string.IsNullOrWhiteSpace(orderby))
  1526. {
  1527. sb.Append(" ");
  1528. sb.Append(orderby);
  1529. }
  1530. sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
  1531. #endregion
  1532. break;
  1533. case "sqlite":
  1534. #region 分页查询语句
  1535. commandText = string.Format("select count(*) from ({0}) T", sql);
  1536. cmd = GetCommand(commandText, connection);
  1537. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1538. totalCount = int.Parse(cmd.ExecuteScalar().ToString());
  1539.  
  1540. startRow = pageSize * (currentPage - );
  1541.  
  1542. sb.Append(sql);
  1543. if (!string.IsNullOrWhiteSpace(orderby))
  1544. {
  1545. sb.Append(" ");
  1546. sb.Append(orderby);
  1547. }
  1548. sb.AppendFormat(" limit {0} offset {1}", pageSize, startRow);
  1549. #endregion
  1550. break;
  1551. case "access":
  1552. #region 分页查询语句
  1553. commandText = string.Format("select count(*) from ({0}) T", sql);
  1554. cmd = GetCommand(commandText, connection);
  1555. foreach (DbParameter parm in cmdParms) cmd.Parameters.Add(parm);
  1556. totalCount = int.Parse(cmd.ExecuteScalar().ToString());
  1557. cmd.Parameters.Clear();
  1558.  
  1559. endRow = pageSize * currentPage;
  1560. startRow = pageSize * currentPage > totalCount ? totalCount - pageSize * (currentPage - ) : pageSize;
  1561. if (startRow <= ) { return null; }
  1562. string[] orderbyArr = string.Format("{0} asc", orderby.Trim()).Split(' ');
  1563.  
  1564. sb.AppendFormat(@"
  1565. select * from(
  1566. select top {4} * from
  1567. (select top {3} * from ({0}) order by {1} asc)
  1568. order by {1} desc
  1569. ) order by {1} {2}", sql, orderbyArr[], orderbyArr[], endRow, startRow);
  1570. #endregion
  1571. break;
  1572. }
  1573.  
  1574. ds = Query(sql, cmdParms);
  1575. }
  1576. return ds;
  1577. }
  1578. #endregion
  1579.  
  1580. #region getReaderValue 转换数据
  1581. /// <summary>
  1582. /// 转换数据
  1583. /// </summary>
  1584. private static Object getReaderValue(Object rdValue, Type ptype)
  1585. {
  1586. if (ptype == typeof(double))
  1587. return Convert.ToDouble(rdValue);
  1588.  
  1589. if (ptype == typeof(decimal))
  1590. return Convert.ToDecimal(rdValue);
  1591.  
  1592. if (ptype == typeof(int))
  1593. return Convert.ToInt32(rdValue);
  1594.  
  1595. if (ptype == typeof(long))
  1596. return Convert.ToInt64(rdValue);
  1597.  
  1598. if (ptype == typeof(DateTime))
  1599. return Convert.ToDateTime(rdValue);
  1600.  
  1601. if (ptype == typeof(Nullable<double>))
  1602. return Convert.ToDouble(rdValue);
  1603.  
  1604. if (ptype == typeof(Nullable<decimal>))
  1605. return Convert.ToDecimal(rdValue);
  1606.  
  1607. if (ptype == typeof(Nullable<int>))
  1608. return Convert.ToInt32(rdValue);
  1609.  
  1610. if (ptype == typeof(Nullable<long>))
  1611. return Convert.ToInt64(rdValue);
  1612.  
  1613. if (ptype == typeof(Nullable<DateTime>))
  1614. return Convert.ToDateTime(rdValue);
  1615.  
  1616. return rdValue;
  1617. }
  1618. #endregion
  1619.  
  1620. #region 获取主键名称
  1621. /// <summary>
  1622. /// 获取主键名称
  1623. /// </summary>
  1624. public static string GetIdName(Type type)
  1625. {
  1626. PropertyInfo[] propertyInfoList = GetEntityProperties(type);
  1627. foreach (PropertyInfo propertyInfo in propertyInfoList)
  1628. {
  1629. if (propertyInfo.GetCustomAttributes(typeof(IsIdAttribute), false).Length > )
  1630. {
  1631. return propertyInfo.Name;
  1632. }
  1633. }
  1634. return "Id";
  1635. }
  1636. #endregion
  1637.  
  1638. #region 获取主键值
  1639. /// <summary>
  1640. /// 获取主键名称
  1641. /// </summary>
  1642. public static object GetIdVal(object val)
  1643. {
  1644. string idName = GetIdName(val.GetType());
  1645. if (!string.IsNullOrWhiteSpace(idName))
  1646. {
  1647. return val.GetType().GetProperty(idName).GetValue(val, null);
  1648. }
  1649. return ;
  1650. }
  1651. #endregion
  1652.  
  1653. #region 获取实体类属性
  1654. /// <summary>
  1655. /// 获取实体类属性
  1656. /// </summary>
  1657. private static PropertyInfo[] GetEntityProperties(Type type)
  1658. {
  1659. List<PropertyInfo> result = new List<PropertyInfo>();
  1660. PropertyInfo[] propertyInfoList = type.GetProperties();
  1661. foreach (PropertyInfo propertyInfo in propertyInfoList)
  1662. {
  1663. if (propertyInfo.GetCustomAttributes(typeof(EdmRelationshipNavigationPropertyAttribute), false).Length ==
  1664. && propertyInfo.GetCustomAttributes(typeof(BrowsableAttribute), false).Length == )
  1665. {
  1666. result.Add(propertyInfo);
  1667. }
  1668. }
  1669. return result.ToArray();
  1670. }
  1671. #endregion
  1672.  
  1673. #region 获取基类
  1674. /// <summary>
  1675. /// 获取基类
  1676. /// </summary>
  1677. public static Type GetBaseType(Type type)
  1678. {
  1679. while (type.BaseType != null && type.BaseType.Name != typeof(Object).Name)
  1680. {
  1681. type = type.BaseType;
  1682. }
  1683. return type;
  1684. }
  1685. #endregion
  1686. #endregion
  1687.  
  1688. #region 事务
  1689. #region 开始事务
  1690. /// <summary>
  1691. /// 开始事务
  1692. /// </summary>
  1693. public static void BeginTransaction()
  1694. {
  1695. DbConnection conn = GetConnection();
  1696. if (conn.State != ConnectionState.Open) conn.Open();
  1697. m_Tran = conn.BeginTransaction();
  1698. }
  1699. #endregion
  1700.  
  1701. #region 提交事务
  1702. /// <summary>
  1703. /// 提交事务
  1704. /// </summary>
  1705. public static void CommitTransaction()
  1706. {
  1707. if (m_Tran == null) return; //防止重复提交
  1708. DbConnection conn = m_Tran.Connection;
  1709. try
  1710. {
  1711. m_Tran.Commit();
  1712. }
  1713. catch (Exception ex)
  1714. {
  1715. m_Tran.Rollback();
  1716. }
  1717. finally
  1718. {
  1719. if (conn.State == ConnectionState.Open) conn.Close();
  1720. m_Tran.Dispose();
  1721. m_Tran = null;
  1722. }
  1723. }
  1724. #endregion
  1725.  
  1726. #region 回滚事务(出错时调用该方法回滚)
  1727. /// <summary>
  1728. /// 回滚事务(出错时调用该方法回滚)
  1729. /// </summary>
  1730. public static void RollbackTransaction()
  1731. {
  1732. if (m_Tran == null) return; //防止重复回滚
  1733. DbConnection conn = m_Tran.Connection;
  1734. m_Tran.Rollback();
  1735. if (conn.State == ConnectionState.Open) conn.Close();
  1736. }
  1737. #endregion
  1738. #endregion
  1739.  
  1740. }
  1741. }

说明:DBHelper中对事务变量private static DbTransaction m_Tran使用了[ThreadStatic]标签,以支持多用户并发;但是如果是单个用户使用多线程并发请求服务器,可能这种方式的数据库事务是不支持的,不过一般项目没有这种需求,如果有请使用HttpContext.Current.Items改写或者其它方法改写。

Web.config配置:

  1. <connectionStrings>
  2. <add name="DefaultConnection" connectionString="server=localhost;database=netcms3.0;user id=root;password=root;character set=gbk;" />
  3. </connectionStrings>
  4. <appSettings>
  5. <!--数据库类型-->
  6. <add key="DBType" value="mysql"/>
  7. <!--数据库自增-->
  8. <add key="AutoIncrement" value="false"/>
  9. </appSettings>

说明:对于SQL Server数据库,通过<add key="AutoIncrement" value="false"/>来设置是否使用数据库自增。

DBHelper类库需要引用的程序集:

除VS2012自带的DLL外需要的DLL:

MySql.Data.dll

System.Data.SQLite.dll

其中Models类库如下:

说明:Models目录中的类及其属性和数据库中的表和字段是完全对应的,Models全部由生成器生成,并且不允许手动修改。ExtModels目录中的类是扩展类,主要用于查询与显示,比如表中存的是code,但你需要关联查询另一张表中的name,就可以在这个扩展类中扩展一个用于显示的name字段。Models和ExtModels目录的中类都是partial修饰。

PagerModel类:

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6.  
  7. namespace Models
  8. {
  9. /// <summary>
  10. /// 分页
  11. /// </summary>
  12. public class PagerModel
  13. {
  14. #region 字段
  15. /// <summary>
  16. /// 当前页数
  17. /// </summary>
  18. public int page { get; set; }
  19. /// <summary>
  20. /// 每页记录数
  21. /// </summary>
  22. public int rows { get; set; }
  23. /// <summary>
  24. /// 排序字段
  25. /// </summary>
  26. public string sort { get; set; }
  27. /// <summary>
  28. /// 排序的方式asc,desc
  29. /// </summary>
  30. public string order { get; set; }
  31. /// <summary>
  32. /// 记录
  33. /// </summary>
  34. public object result { get; set; }
  35. /// <summary>
  36. /// 记录数
  37. /// </summary>
  38. public int totalRows { get; set; }
  39. #endregion
  40.  
  41. #region 构造函数
  42. public PagerModel()
  43. {
  44.  
  45. }
  46. /// <summary>
  47. ///
  48. /// </summary>
  49. /// <param name="page">当前页数</param>
  50. /// <param name="rows">每页记录数</param>
  51. public PagerModel(int page, int rows)
  52. {
  53. this.page = page;
  54. this.rows = rows;
  55. }
  56. #endregion
  57.  
  58. #region 扩展字段
  59. /// <summary>
  60. /// 总页数
  61. /// </summary>
  62. public int pageCount
  63. {
  64. get
  65. {
  66. return (totalRows - ) / rows + ;
  67. }
  68. }
  69. /// <summary>
  70. /// 上一页
  71. /// </summary>
  72. public int prePage
  73. {
  74. get
  75. {
  76. if (page - > )
  77. {
  78. return page - ;
  79. }
  80. return ;
  81. }
  82. }
  83. /// <summary>
  84. /// 下一页
  85. /// </summary>
  86. public int nextPage
  87. {
  88. get
  89. {
  90. if (page + < pageCount)
  91. {
  92. return page + ;
  93. }
  94. return pageCount;
  95. }
  96. }
  97. #endregion
  98.  
  99. }
  100. }

IsIdAttribute类:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Models
  7. {
  8. /// <summary>
  9. /// 标识该属性是主健
  10. /// </summary>
  11. [Serializable, AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
  12. public class IsIdAttribute : Attribute
  13. {
  14. }
  15. }

IsDBFieldAttribute类:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Models
  7. {
  8. /// <summary>
  9. /// 标识该属性是数据库字段
  10. /// </summary>
  11. [Serializable, AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
  12. public class IsDBFieldAttribute : Attribute
  13. {
  14. }
  15. }

Models示例:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Models
  6. {
  7. /// <summary>
  8. /// 内容详情
  9. /// </summary>
  10. [Serializable]
  11. public partial class cms_content
  12. {
  13. /// <summary>
  14. /// 编号
  15. /// </summary>
  16. [IsId]
  17. [IsDBField]
  18. public int id { get; set; }
  19. /// <summary>
  20. /// 所属栏目ID
  21. /// </summary>
  22. [IsDBField]
  23. public int? channelId { get; set; }
  24. /// <summary>
  25. /// 标题
  26. /// </summary>
  27. [IsDBField]
  28. public string title { get; set; }
  29. /// <summary>
  30. /// 内容
  31. /// </summary>
  32. [IsDBField]
  33. public string contents { get; set; }
  34. /// <summary>
  35. /// 作者
  36. /// </summary>
  37. [IsDBField]
  38. public string author { get; set; }
  39. /// <summary>
  40. /// 阅读次数
  41. /// </summary>
  42. [IsDBField]
  43. public int? readCount { get; set; }
  44. /// <summary>
  45. /// 发布时间
  46. /// </summary>
  47. [IsDBField]
  48. public DateTime? publishTime { get; set; }
  49. /// <summary>
  50. /// 发布者
  51. /// </summary>
  52. [IsDBField]
  53. public int? publishUserId { get; set; }
  54. /// <summary>
  55. /// 审核(0待审1通过2不通过)
  56. /// </summary>
  57. [IsDBField]
  58. public int? audit { get; set; }
  59. /// <summary>
  60. /// 审核人
  61. /// </summary>
  62. [IsDBField]
  63. public int? auditUserId { get; set; }
  64. /// <summary>
  65. /// 审核时间
  66. /// </summary>
  67. [IsDBField]
  68. public DateTime? auditTime { get; set; }
  69. /// <summary>
  70. /// 页面关键词
  71. /// </summary>
  72. [IsDBField]
  73. public string keywords { get; set; }
  74. /// <summary>
  75. /// 页面描述
  76. /// </summary>
  77. [IsDBField]
  78. public string description { get; set; }
  79. /// <summary>
  80. /// 页面链接
  81. /// </summary>
  82. [IsDBField]
  83. public string pageUrl { get; set; }
  84. /// <summary>
  85. /// 内容封面
  86. /// </summary>
  87. [IsDBField]
  88. public string imgUrl { get; set; }
  89. /// <summary>
  90. /// 是否链接(0否1是)
  91. /// </summary>
  92. [IsDBField]
  93. public int? isPageUrl { get; set; }
  94. /// <summary>
  95. /// 模板(模板文件名,例:content.html)
  96. /// </summary>
  97. [IsDBField]
  98. public string template { get; set; }
  99. /// <summary>
  100. /// 推荐(1推荐0不推荐)
  101. /// </summary>
  102. [IsDBField]
  103. public int? recommend { get; set; }
  104. }
  105. }

ExtModels示例:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Models
  6. {
  7. /// <summary>
  8. /// 内容详情
  9. /// </summary>
  10. public partial class cms_content
  11. {
  12. /// <summary>
  13. /// 栏目名称
  14. /// </summary>
  15. public string channelName { get; set; }
  16. /// <summary>
  17. /// 用户显示名
  18. /// </summary>
  19. public string showName { get; set; }
  20. /// <summary>
  21. /// 审核状态
  22. /// </summary>
  23. public string dispAudit
  24. {
  25. get
  26. {
  27. switch (this.audit ?? )
  28. {
  29. case :
  30. return "待审核";
  31. case :
  32. return "审核通过";
  33. case :
  34. return "审核不通过";
  35. }
  36. return "error";
  37. }
  38. set { }
  39. }
  40. /// <summary>
  41. /// 在当前页中的索引
  42. /// </summary>
  43. public int curPageSort { get; set; }
  44. /// <summary>
  45. /// 是否为空,模板使用,0不为空1为空
  46. /// </summary>
  47. public int isNull { get; set; }
  48. }
  49. }

如何使用:

说明:支持参数化的增删改查,推荐使用参数化的增删改查;非参数化的增删改查过滤了部分数据库关键字以防止SQL注入,但可能仍然不安全。下面例子中的添加、修改、根据ID删除、根据ID集合批量删除都是参数化的,示例中的查询和其它方式的删除不是参数化的,DBHelper提供了相关的参数化查询和执行SQL。

添加:

  1. /// <summary>
  2. /// 添加
  3. /// </summary>
  4. public void Insert(object obj)
  5. {
  6. DBHelper.Insert(obj);
  7. }

说明:SQL Server数据库可以使用自增,Oracle数据库可以使用Sequence,小系统可以使用DBHelper自带的GetMaxID方法。

获取最大ID(当然,ID一般采用自增,对于并发量极少的系统,或单机系统,为了省事,可以这样做):

  1. /// <summary>
  2. /// GetMaxId
  3. /// </summary>
  4. public int GetMaxId()
  5. {
  6. return DBHelper.GetMaxID<BS_Template>("id");
  7. }

修改:

  1. /// <summary>
  2. /// 修改
  3. /// </summary>
  4. public void Update(object obj)
  5. {
  6. DBHelper.Update(obj);
  7. }

删除:

根据ID删除:

  1. /// <summary>
  2. /// 删除
  3. /// </summary>
  4. public void Del(int id)
  5. {
  6. DBHelper.Delete<BS_Template>(id);
  7. }

根据ID集合批量删除:

  1. /// <summary>
  2. /// 删除
  3. /// </summary>
  4. public void BatchDelete(string ids)
  5. {
  6. DBHelper.BatchDelete<BS_Template>(ids);
  7. }

根据条件删除:

  1. /// <summary>
  2. /// 删除
  3. /// </summary>
  4. public void Delete(string conditions)
  5. {
  6. DBHelper.Delete<BS_Template>(conditions);
  7. }

其它方式的删除请使用:

public static int ExecuteSql(string sqlString)

根据ID查询实体:

  1. public cms_content Get(int id)
  2. {
  3. return DBHelper.FindById<cms_content>(id.ToString());
  4. }

查询:

  1. public List<cms_content> GetListAll()
  2. {
  3. StringBuilder sql = new StringBuilder(string.Format(@"
  4. select content.*, channel.title as channelName, user.showName
  5. from cms_content content
  6. left join cms_channel channel on channel.id=content.channelId
  7. left join CMS_sys_user user on user.id=content.publishUserId
  8. where content.audit=1
  9. order by publishTime desc,id desc"));
  10.  
  11. return DBHelper.FindListBySql<cms_content>(sql.ToString());
  12. }

说明:ExtModels下的扩展Model,可以支持查询数据库中不存在的字段,并映射填充到实体类。

分页查询:

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

数据库事务:

  1. try
  2. {
  3. DBHelper.BeginTransaction(); //开启数据库事务
  4.  
  5. //在这里写增删改操作
  6.  
  7. DBHelper.CommitTransaction(); //提交数据库事务
  8. }catch(Exception ex)
  9. {
  10. DBHelper.RollbackTransaction(); //回滚数据库事务
  11. }

DAL层增删改查示例:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using DBUtil;
  7. using Models;
  8.  
  9. namespace DAL
  10. {
  11. /// <summary>
  12. /// 内容详情管理
  13. /// </summary>
  14. public class ContentDal
  15. {
  16. #region 获取列表
  17. /// <summary>
  18. /// 获取列表
  19. /// </summary>
  20. public List<cms_content> GetList(ref PagerModel pager, int channelId, string title, int audit)
  21. {
  22. StringBuilder sql = new StringBuilder(string.Format(@"
  23. select content.*, channel.title as channelName, user.showName
  24. from cms_content content
  25. left join cms_channel channel on channel.id=content.channelId
  26. left join CMS_sys_user user on user.id=content.publishUserId
  27. where 1=1 "));
  28.  
  29. if (channelId != -)
  30. {
  31. sql.AppendFormat(" and content.channelId = {0}", channelId);
  32. }
  33. if (!string.IsNullOrWhiteSpace(title))
  34. {
  35. sql.AppendFormat(" and content.title like '%{0}%'", title);
  36. }
  37. if (audit != -)
  38. {
  39. sql.AppendFormat(" and content.audit = {0}", audit);
  40. }
  41.  
  42. string orderby = string.Format("order by content.publishTime desc,id desc");
  43. pager = DBHelper.FindPageBySql<cms_content>(sql.ToString(), orderby, pager.rows, pager.page);
  44. return pager.result as List<cms_content>;
  45. }
  46. #endregion
  47.  
  48. #region 获取列表
  49. /// <summary>
  50. /// 获取列表
  51. /// </summary>
  52. /// <param name="pager">分页</param>
  53. /// <param name="channel">栏目,可以是栏目ID或栏目名称</param>
  54. /// <param name="where">where语句</param>
  55. public List<cms_content> GetList(ref PagerModel pager, string channel, string where)
  56. {
  57. StringBuilder sql = new StringBuilder(string.Format(@"
  58. select content.*, channel.title as channelName, user.showName
  59. from cms_content content
  60. left join cms_channel channel on channel.id=content.channelId
  61. left join CMS_sys_user user on user.id=content.publishUserId
  62. where content.audit=1 "));
  63.  
  64. if (!string.IsNullOrWhiteSpace(where))
  65. {
  66. sql.AppendFormat(" and {0}", where);
  67. }
  68.  
  69. if (!string.IsNullOrWhiteSpace(channel))
  70. {
  71. ChannelDal channelDal = new ChannelDal();
  72. if (Regex.IsMatch(channel, @"^\d+$")) //数字,即栏目ID
  73. {
  74. string channelIds = channelDal.GetChildIds(Convert.ToInt32(channel));
  75. sql.AppendFormat(" and channelId in ({0})", channelIds);
  76. }
  77. else //非数字,即栏目名称
  78. {
  79. string channelIds = channelDal.GetChildIds(channel);
  80. sql.AppendFormat(" and channelId in ({0})", channelIds);
  81. }
  82. }
  83.  
  84. string orderby = string.Format("order by publishTime desc,id desc");
  85. if (pager.rows > )
  86. {
  87. PagerModel pagerModel = DBHelper.FindPageBySql<cms_content>(sql.ToString(), orderby, pager.rows, pager.page);
  88. pager.totalRows = pagerModel.totalRows;
  89. pager.result = pagerModel.result;
  90. List<cms_content> list = pagerModel.result as List<cms_content>;
  91. int i = ;
  92. list.ForEach(a =>
  93. {
  94. a.curPageSort = i++;
  95. });
  96. return pagerModel.result as List<cms_content>;
  97. }
  98. else
  99. {
  100. return DBHelper.FindListBySql<cms_content>(sql.ToString() + orderby);
  101. }
  102. }
  103. #endregion
  104.  
  105. #region 获取列表
  106. /// <summary>
  107. /// 获取列表
  108. /// </summary>
  109. public List<cms_content> GetListAll()
  110. {
  111. StringBuilder sql = new StringBuilder(string.Format(@"
  112. select content.*, channel.title as channelName, user.showName
  113. from cms_content content
  114. left join cms_channel channel on channel.id=content.channelId
  115. left join CMS_sys_user user on user.id=content.publishUserId
  116. where content.audit=1
  117. order by publishTime desc,id desc"));
  118.  
  119. return DBHelper.FindListBySql<cms_content>(sql.ToString());
  120. }
  121. #endregion
  122.  
  123. #region 获取总数
  124. /// <summary>
  125. /// 获取总数
  126. /// </summary>
  127. public int GetAllCount()
  128. {
  129. StringBuilder sql = new StringBuilder(string.Format(@"
  130. select count(*)
  131. from cms_content content
  132. where content.audit=1"));
  133.  
  134. return Convert.ToInt32(DBHelper.GetSingle(sql.ToString()));
  135. }
  136. #endregion
  137.  
  138. #region 获取
  139. /// <summary>
  140. /// 获取
  141. /// </summary>
  142. public cms_content Get(int id)
  143. {
  144. return DBHelper.FindById<cms_content>(id.ToString());
  145. }
  146. /// <summary>
  147. /// 根据channelId获取一条内容详情
  148. /// </summary>
  149. public cms_content GetByChannelId(int channelId)
  150. {
  151. return DBHelper.FindBySql<cms_content>(string.Format("select * from cms_content where channelId={0} and audit=1", channelId));
  152. }
  153. /// <summary>
  154. /// 获取
  155. /// </summary>
  156. public cms_content GetNext(int id)
  157. {
  158. cms_content current = Get(id);
  159. return DBHelper.FindBySql<cms_content>(string.Format("select * from cms_content where id<{0} and channelId={1} and audit=1 order by id desc limit 0,1", current.id, current.channelId));
  160. }
  161. /// <summary>
  162. /// 获取
  163. /// </summary>
  164. public cms_content GetPre(int id)
  165. {
  166. cms_content current = Get(id);
  167. return DBHelper.FindBySql<cms_content>(string.Format("select * from cms_content where id>{0} and channelId={1} and audit=1 order by id asc limit 0,1", current.id, current.channelId));
  168. }
  169. #endregion
  170.  
  171. #region 添加
  172. /// <summary>
  173. /// 添加
  174. /// </summary>
  175. public void Insert(cms_content model)
  176. {
  177. model.id = DBHelper.GetMaxID<cms_content>("id");
  178. DBHelper.Insert(model);
  179. }
  180. #endregion
  181.  
  182. #region 修改
  183. /// <summary>
  184. /// 修改
  185. /// </summary>
  186. public void Update(cms_content model)
  187. {
  188. DBHelper.Update(model);
  189. }
  190. #endregion
  191.  
  192. #region 删除
  193. /// <summary>
  194. /// 删除
  195. /// </summary>
  196. public void Del(string ids)
  197. {
  198. DBHelper.BatchDelete<cms_content>(ids);
  199. }
  200. #endregion
  201.  
  202. }
  203. }

例子代码下载:http://files.cnblogs.com/files/s0611163/DBHelperDemo.zip

说明:例子程序是Winform,该DBHelper也适用于Web项目。

配套Model生成器下载:

链接: https://pan.baidu.com/s/1QR7fjXvNyQKGzZ2_2XV0AQ 提取码: kgsq

http://files.cnblogs.com/files/s0611163/Model%E7%94%9F%E6%88%90%E5%99%A8.zip

如果您不明白我为什么要写DBHelper,为什么没有语法糖,为什么查询和分页查询要使用原生SQL,看看下面我们ERP项目中的代码,你会明白,当然,这个项目设计的确实不好:

1、

  1. /// <summary>
  2. /// 统计SQL
  3. /// </summary>
  4. public override string GetReportSql(string formData)
  5. {
  6. ProductInvoiceModel search = JsonConvert.DeserializeObject<ProductInvoiceModel>(formData);
  7.  
  8. StringBuilder sql = new StringBuilder(string.Format(@"
  9. select * from
  10. (select distinct
  11. '出库单' as '报表类型',
  12. pos.billNo as '单据编号',
  13. pos.projectCode as '项目编号',
  14. pro.projectName as '项目名称',
  15. ma.subProject as '项目子项',
  16.  
  17. case when cs.conMemberCode is not NULL then cs.conMemberCode else mat.materialCode end as '构件编码',
  18. case when cmd.memberName is not NULL then cmd.memberName else mat.materialName end as '材料名称',
  19. case when cs.conMemberCode is not NULL then '构件' else '物料' end as '类型',
  20.  
  21. mad.model as '规格型号',
  22. dic1.dicItem as '单位',
  23. posd.qty as '数量',
  24.  
  25. CONVERT(varchar(100), pos.billDate, 23) as '日期'
  26.  
  27. from Pro_ProductOutStorageDet posd
  28. left join Pro_ProductOutStorage pos on pos.id=posd.parentId
  29.  
  30. left join Pro_MatAllotDet mad on posd.matAllotDetId=mad.id
  31. left join Pro_MatAllot ma on ma.id=mad.parentID and ma.status=2
  32. left join Pro_MatStock ms on ms.id=mad.matStockId and mad.memberType=1
  33. left join Pro_ConStock cs on cs.id=mad.matStockId and mad.memberType=0
  34. left join sys_material mat on mat.materialCode=ms.materailCode
  35.  
  36. left join Pro_ProductInstorage pi on pi.billNo=cs.billNo
  37. left join Pro_ProductInstorageDet pid on pid.parentId=pi.id
  38.  
  39. left join Pro_ConMember cm on cm.billCode=pi.conMemberBillNo
  40. left join Pro_ConMemberDet cmd on cmd.id=pid.conMemberDetId
  41.  
  42. left join Pro_Info pro on pos.projectCode=pro.projectNum
  43.  
  44. left join sys_dicDetail dic1 on dic1.dicItemcode=mad.unitCode
  45.  
  46. union all
  47.  
  48. select distinct
  49. 'XXX出库单' as '报表类型',
  50. pos.billNo as '单据编号',
  51. pos.projectCode as '项目编号',
  52. pro.projectName as '项目名称',
  53. '' as '项目子项',
  54.  
  55. case when cs.conMemberCode is not NULL then cs.conMemberCode else mat.materialCode end as '构件编码',
  56. case when cmd.memberName is not NULL then cmd.memberName else mat.materialName end as '材料名称',
  57. case when cs.conMemberCode is not NULL then '构件' else '物料' end as '类型',
  58.  
  59. case when cmd.model is not NULL then cmd.model else mat.model end as '规格型号',
  60. case when dic1.dicItem is not NULL then dic1.dicItem else dic2.dicItem end as '单位',
  61. posd.qty as '数量',
  62.  
  63. CONVERT(varchar(100), pos.billDate, 23) as '日期'
  64.  
  65. from Pro_ProductOut2StorageDet posd
  66. left join Pro_ProductOut2Storage pos on pos.id=posd.parentId
  67.  
  68. left join Pro_MatStock ms on ms.id=posd.matStockId
  69. left join Pro_ConStock cs on cs.id=posd.conInventoryDetId
  70. left join sys_material mat on mat.materialCode=ms.materailCode
  71.  
  72. left join Pro_ProductInstorage pi on pi.billNo=cs.billNo
  73. left join Pro_ProductInstorageDet pid on pid.parentId=pi.id
  74.  
  75. left join Pro_ConMember cm on cm.billCode=pi.conMemberBillNo
  76. left join Pro_ConMemberDet cmd on cmd.id=pid.conMemberDetId
  77.  
  78. left join Pro_Info pro on pos.projectCode=pro.projectNum
  79.  
  80. left join sys_dicDetail dic1 on dic1.dicItemcode=mat.unitCode
  81. left join sys_dicDetail dic2 on dic2.dicItemcode=cmd.qtyUnit
  82.  
  83. union all
  84.  
  85. select distinct
  86. '生产消耗单' as '报表类型',
  87. pc.billCode as '单据编号',
  88. pro.projectNum as '项目编号',
  89. pro.projectName as '项目名称',
  90. ll.subProject as '项目子项',
  91.  
  92. case when cs.conMemberCode is not NULL then cs.conMemberCode else mat.materialCode end as '构件编码',
  93. case when cmd.memberName is not NULL then cmd.memberName else mat.materialName end as '材料名称',
  94. case when cs.conMemberCode is not NULL then '构件' else '物料' end as '类型',
  95.  
  96. case when cmd.model is not NULL then cmd.model else mat.model end as '规格型号',
  97. case when dic1.dicItem is not NULL then dic1.dicItem else dic2.dicItem end as '单位',
  98. pcd.consumeQty as '数量',
  99.  
  100. CONVERT(varchar(100), pc.billDate, 23) as '日期'
  101.  
  102. from Pro_ProductConsume pc
  103. left join Pro_ProductConsumeDet pcd on pcd.parentId=pc.id
  104.  
  105. left join Pro_LingLiaoDet lld on lld.id=pcd.lingLiaoDetId
  106. left join Pro_LingLiao ll on ll.id=lld.parentId
  107.  
  108. left join Pro_MatStock ms on ms.id=lld.matStockId and lld.memberType=1
  109. left join Pro_ConStock cs on cs.id=lld.matStockId and lld.memberType=0
  110. left join sys_material mat on mat.materialCode=ms.materailCode
  111.  
  112. left join Pro_ProductInstorage pi on pi.billNo=cs.billNo
  113. left join Pro_ProductInstorageDet pid on pid.parentId=pi.id
  114.  
  115. left join Pro_ConMember cm on cm.billCode=pi.conMemberBillNo
  116. left join Pro_ConMemberDet cmd on cmd.id=pid.conMemberDetId
  117.  
  118. left join Pro_ProTask pt on pt.billCode=ll.proTaskCode
  119. left join Pro_Info pro on pt.proInfCode=pro.billCode
  120.  
  121. left join sys_dicDetail dic1 on dic1.dicItemcode=mat.unitCode
  122. left join sys_dicDetail dic2 on dic2.dicItemcode=cmd.qtyUnit
  123. ) T where 1=1 "));
  124.  
  125. if (!string.IsNullOrEmpty(search.projectName))
  126. {
  127. sql.AppendFormat(" and T.项目名称 like '%{0}%' ", search.projectName.Trim());
  128. }
  129. if (!string.IsNullOrEmpty(search.projectCode))
  130. {
  131. sql.AppendFormat(" and T.项目编号 like '%{0}%' ", search.projectCode.Trim());
  132. }
  133. if (!string.IsNullOrEmpty(search.btime) && !string.IsNullOrEmpty(search.etime))
  134. {
  135. sql.AppendFormat(" and T.日期 >= '{0}'", search.btime);
  136. }
  137. if (!string.IsNullOrEmpty(search.etime))
  138. {
  139. sql.AppendFormat(" and T.日期 <= '{0}'", search.etime);
  140. }
  141.  
  142. return sql.ToString();
  143. }

说明:查询SQL书写规范:SQL不能写的乱七八糟,该换行换行,该对齐对齐。

2、

  1. public List<MatAllotModel> GeProMatAllotList(ref PagerModel pager, string billCode, string projectNum, string projectName, string remarks, int status)
  2. {
  3. string sql = @"select v.*,ISNULL(v.IsFinish,(case when ISNULL(v.pqty,0)= ISNULL(v.mqty,0) then 1 else 0 end)) as IsEnd from (
  4. select ma.*,e.name + '('+isnull(e.mobilephone,'')+')' as billCreatorName,i.projectName,s.storeHouseName as inStoreName,
  5. (select stuff((select distinct ','+s.storeHouseName from Pro_MatAllotDet mad
  6. join sys_storehouse s on mad.outStorageCode=s.storeHouseCode
  7. where parentId =ma.id for xml path('')),1,1,'')) as outStoreName,I.projectSim,D.dicItem AS typename,ppi.id as InvoiceId,i.projectNum,
  8. (select sum(md.qty) from Pro_MatAllotDet md where md.parentId =ma.id) as mqty,
  9. (select sum(qty) from Pro_ProductOutStorageDet pod
  10. left join Pro_ProductOutStorage po on po.id = pod.parentID
  11. where po.matAllotBillCode = ma.billCode) as pqty
  12. from Pro_MatAllot ma
  13. join sys_storehouse s on ma.inStoreCode=s.storeHouseCode
  14. join sys_employee e on ma.billCreator=e.employeeCode
  15. left join Pro_ProductInvoice ppi on ppi.MatAllotBillCode=ma.billCode
  16. left join Pro_Info i on ma.projectCode = i.projectNum
  17. LEFT JOIN sys_dicDetail D ON D.dicItemcode = I.projectType
  18. ) as v where 1=1 ";
  19. if (!string.IsNullOrEmpty(billCode))
  20. {
  21. sql += " and v.billCode like '%" + billCode.Trim() + "%'";
  22. }
  23. if (!string.IsNullOrEmpty(projectName))
  24. {
  25. sql += " and v.projectName like '%" + projectName.Trim() + "%'";
  26. }
  27. if (!string.IsNullOrEmpty(projectNum))
  28. {
  29. sql += " and v.projectNum like '%" + projectNum.Trim() + "%'";
  30. }
  31. if (!string.IsNullOrEmpty(remarks))
  32. {
  33. sql += " and v.remarks like '%" + remarks.Trim() + "%'";
  34. }
  35. sql += " and v.status=" + status + "";
  36. List<MatAllotModel> matAllot = EntityHelper.Default.GetPageEntities<MatAllotModel>(pager.page, pager.rows, sql, "id", pager.sort, pager.order);
  37. pager.totalRows = DBHelper.Default.Count(sql);
  38. pager.result = matAllot;
  39. return matAllot;
  40. }

3、

  1. public static List<ConStockDialogMod> GetMaterialData(ref PagerModel pager, string memberName, string storeCode, string parentId, string store)
  2. {
  3. StringBuilder where = new StringBuilder(" and 1=1 ");
  4. if (!string.IsNullOrEmpty(memberName)) //当物料为空时,查询出所有的结果集,否则查询出此种相似物料的结果集
  5. where.AppendFormat(" and t3.memberName like '%{0}%' ", memberName.Trim());
  6. if (!string.IsNullOrEmpty(storeCode)) //当物料为空时,查询出所有的结果集,否则查询出此种相似物料的结果集
  7. where.AppendFormat(" and SSH.storeHouseCode='{0}' ", storeCode);
  8. if (!string.IsNullOrEmpty(parentId)) //当物料为空时,查询出所有的结果集,否则查询出此种相似物料的结果集
  9. where.AppendFormat(" and t3.parentId = {0} ", parentId);
  10. if (!string.IsNullOrEmpty(store))
  11. where.AppendFormat(" and SSH.storeHouseName like '%{0}%' ", store.Trim());
  12. string sql = @"SELECT PM.id,PM.conMemberCode as conMemberCode,PM.price,(PM.qty-PM.lockQty-PM.usedQty) AS stockNum,
  13. PM.instoreTime,PM.billNo,PM.storeCode,PM.lockQty,PM.usedQty,SSH.storeHouseName AS storeName,
  14. t3.allWeight,t3.qtyUnit,t3.weight as weights,t3.memberName,t3.model,t3.qulity,
  15. d1.dicItem as allWeightUnitName,d2.dicItem as qtyUnitName,
  16. d3.dicItem as qulityName,d4.dicItem as weightUnitName,
  17. (select SUM(pt.qty) from Pro_ProductOutstorageDet pt where pt.conInventoryDetId=PM.id)as outQty
  18. from Pro_ConStock PM
  19. join Pro_ConPurInstore cpd on PM.billNo=cpd.billCode
  20. join Pro_ConPurInstoreDet cp on cpd.id=cp.parentId and PM.billId=cp.id
  21. join dbo.Pro_ConGoodsDet t on t.id=cp.conGoodsDetId
  22. join dbo.Pro_ConPurchaseContractDet t1 on t1.id=t.conContractDetId
  23. join dbo.Pro_ConPurchasePlanDet t2 on t2.id=t1.conPlanDetID
  24. join dbo.Pro_ConMemberDet t3 on t3.id=t2.conMemberDetId
  25. left join sys_storehouse SSH on SSH.storeHouseCode=PM.storeCode
  26. left join sys_dicDetail d1 on d1.dicItemcode=t3.allWeightUnit
  27. left join sys_dicDetail d2 on d2.dicItemcode=t3.qtyUnit
  28. left join sys_dicDetail d3 on d3.dicItemcode=t3.qulity
  29. left join sys_dicDetail d4 on d4.dicItemcode=t3.weightUnit
  30. WHERE PM.qty-PM.lockQty-PM.usedQty > 0 " + where +
  31. @" union
  32. SELECT PM.id,PM.conMemberCode as conMemberCode,PM.price,(PM.qty-PM.lockQty-PM.usedQty) AS stockNum,
  33. PM.instoreTime,PM.billNo,PM.storeCode,PM.lockQty,PM.usedQty,
  34. SSH.storeHouseName AS storeName,
  35. t3.allWeight,t3.qtyUnit,t3.weight as weights,t3.memberName,t3.model,t3.qulity,
  36. d1.dicItem as allWeightUnitName,d2.dicItem as qtyUnitName,
  37. d3.dicItem as qulityName,d4.dicItem as weightUnitName,
  38. (select SUM(pt.qty) from Pro_ProductOutstorageDet pt where pt.conInventoryDetId=PM.id)as outQty
  39. from Pro_ConStock PM
  40. join Pro_ProductInstorage cpd on PM.billNo=cpd.billNo
  41. join Pro_ProductInstorageDet cp on cpd.id=cp.parentId and PM.billId=cp.id
  42. join dbo.Pro_ConMemberDet t3 on t3.id=cp.conMemberDetId
  43. left join sys_storehouse SSH on SSH.storeHouseCode=PM.storeCode
  44. left join sys_dicDetail d1 on d1.dicItemcode=t3.allWeightUnit
  45. left join sys_dicDetail d2 on d2.dicItemcode=t3.qtyUnit
  46. left join sys_dicDetail d3 on d3.dicItemcode=t3.qulity
  47. left join sys_dicDetail d4 on d4.dicItemcode=t3.weightUnit
  48. WHERE PM.qty-PM.lockQty-PM.usedQty > 0 " + where;
  49.  
  50. List<ConStockDialogMod> model = EntityHelper.Default.GetPageEntities<ConStockDialogMod>(pager.page, pager.rows, sql.ToString(), "id", pager.sort, pager.order);
  51. pager.totalRows = DBHelper.Default.Count(sql.ToString());
  52. pager.result = model;
  53. return model;
  54.  
  55. }

4、

  1. /// <summary>
  2. /// Sql
  3. /// </summary>
  4. /// <param name="formData"></param>
  5. /// <returns></returns>
  6. public override string GetReportSql(string formData)
  7. {
  8. TaskAllocationModel search = JsonConvert.DeserializeObject<TaskAllocationModel>(formData);
  9. StringBuilder where = new StringBuilder(" where 1=1 ");
  10. if (!string.IsNullOrEmpty(search.projectCode))
  11. {
  12. where.AppendFormat(" and ta.projectCode like '%{0}%' ", search.projectCode.Trim());
  13. }
  14. if (!string.IsNullOrEmpty(search.projectName))
  15. {
  16. where.AppendFormat(" and pro.projectName like '%{0}%' ", search.projectName.Trim());
  17. }
  18. string sql = @"select ta.billCode as '单号',pro.projectName as '项目名称',pro.projectNum as '项目编号',ta.desingBillCode as '项目设计任务单',
  19. CASE ta.violent WHEN '1' THEN '是' ELSE '否' END as '是否加急',
  20. CASE ta.taskType WHEN '0' THEN '载荷图' WHEN '1' THEN '方案图' WHEN '2' THEN '工程量统计' ELSE '载荷图与工程量统计' END as '任务类型',
  21. ta.desingContent as '设计内容',ta.auditorScore as '审核人打分',
  22. (select e.RealName
  23. from Wf2Operate oper
  24. left join Wf2Node n on n.id = oper.Wf2NoteID
  25. left join employee e on e.employeecode = oper.Operator
  26. where Wf2InstanceID = ta.LastWf2InstanceID and n.Name='设计' and oper.OperationID != -3) as '设计者',
  27. (select e.RealName
  28. from Wf2Operate oper
  29. left join Wf2Node n on n.id = oper.Wf2NoteID
  30. left join employee e on e.employeecode = oper.Operator
  31. where Wf2InstanceID = ta.LastWf2InstanceID and n.Name='校对' and oper.OperationID != -3) as '校对者',
  32. (select e.RealName
  33. from Wf2Operate oper
  34. left join Wf2Node n on n.id = oper.Wf2NoteID
  35. left join employee e on e.employeecode = oper.Operator
  36. where Wf2InstanceID = ta.LastWf2InstanceID and n.Name='审核' and oper.OperationID != -3) as '审核者',
  37. (select e.RealName
  38. from Wf2Operate oper
  39. left join Wf2Node n on n.id = oper.Wf2NoteID
  40. left join employee e on e.employeecode = oper.Operator
  41. where Wf2InstanceID = ta.LastWf2InstanceID and n.Name='审定' and oper.OperationID != -3) as '审定者',
  42. e.name as '创建人',ta.creatTime as '创建时间'
  43. from Pro_TaskAllocation ta
  44. left join Pro_Info pro on ta.projectCode=pro.projectNum
  45. left join sys_employee e on ta.creator=e.employeeCode
  46. " + where;
  47.  
  48. return sql.ToString();
  49. }

5、

  1. string sql = string.Format(@"select t.*,t.haveQty as weichukuNum,(t.qty - t.chukuNum) as shenyuNum from (SELECT o.*,(
  2. case memberType when 1 then (SELECT (qty- lockQty- usedQty)
  3. FROM Pro_MatStock s where s.id=o.matStockId )
  4. when 0 then ((SELECT (qty- lockQty- usedQty)
  5. FROM Pro_ConStock s where s.id=o.matStockId )) else 0 end) as haveQty,
  6. (case memberType when 1 then (SELECT materialName from sys_material where materialCode = o.code )
  7. when 0 then (select DISTINCT memberName from Pro_ConMemberDet v LEFT join Pro_ConMember g on g.id=v.parentId where v.memberCode=o.code and g.billCode=ma.conMemberBillNo) else '' end) as materialName
  8. ,sh.storeHouseName as outStorageName ,
  9. isnull((case memberType when 1 then (select SUM(pt.qty) from Pro_ProductOutstorageDet pt LEFT join Pro_ProductOutstorage p on p.id=pt.parentID where pt.matStockId=o.matStockId and p.status in (1,2))
  10. when 0 then (select SUM(pt.qty) from Pro_ProductOutstorageDet pt LEFT join Pro_ProductOutstorage p on p.id=pt.parentID where pt.conInventoryDetId=o.matStockId and p.status in (1,2)) else 0 end),0) as chukuNum,
  11. (case memberType when 1 then (select SUM(ms.qty-ms.lockQty-ms.usedQty) from Pro_MatStock ms where ms.storeCode=ma.inStoreCode AND ms.materailCode =o.code)
  12. when 0 then (select SUM(cs.qty-cs.lockQty-cs.usedQty) from Pro_ConStock cs where cs.storeCode=ma.inStoreCode AND cs.conMemberCode =o.code) else 0 end) as xiangmukuNum
  13. from Pro_MatAllotDet o
  14. JOIN Pro_MatAllot ma on o.parentId = ma.id
  15. join sys_storehouse sh on o.outStorageCode=sh.storeHouseCode
  16. where o.parentId in ({0})) t where t.chukuNum < t.qty", parentId);

C#/ASP.NET完善的DBHelper,配套Model生成器的更多相关文章

  1. ASP.NET Core MVC 中的 Model 模型

    ASP.NET Core MVC 中的 Model 我们希望最终从 Student 数据库表中查询特定的学生详细信息并显示在网页上,如下所示. MVC 中的模型包含一组表示数据的类和管理该数据的逻辑. ...

  2. asp.net mvc5 DataBase First下model校验问题(MetadataType使用)

    最近学习asp.net mvc5,使用   asp.net mvc5+EF6+AutoFac做个小Demo,其中是先设计的数据库表,就直接选择了EF的DataBase First(三种开发模式分别是c ...

  3. asp.net 完善注册登录+sqlite数据库

    结合sqlite数据库,完善asp.net制作的web网页中的注册和登录操作. 1. Account-Register.aspx <%@ Page Title="" Lang ...

  4. 10、ASP.NET MVC入门到精通——Model(模型)和验证

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 模型就是处理业务,想要保存.创建.更新.删除的对象. 注解(通过特性实现) DisplayName Required StringLengt ...

  5. ASP.NET MVC5 学习笔记-3 Model

    1. Model 1.1 添加一个模型 注意,添加属性时可以输入"prop",会自动输入代码段. public class CheckoutAccount { public int ...

  6. iOS开发之遍历Model类的属性并完善使用Runtime给Model类赋值

    在上篇博客<iOS开发之使用Runtime给Model类赋值>中介绍了如何使用运行时在实体类的基类中添加给实体类的属性赋值的方法,这个方法的前提是字典的Key必须和实体类的Property ...

  7. [备忘]Asp.net MVC 将服务端Model传递的对象转为客户端javascript对象

    <script type="text/javascript"> var jsObject = @Html.Raw(Json.Encode(Model.Objects)) ...

  8. asp.net web编程开发将model键值对化

    关键字:model属性,反射 正文         model是数据库的映射,在.net web开发中,作为程序的最底层.web开发的一切都是基于数据库的,分了层之后,就基于model了. 为什么要将 ...

  9. Asp.net MVC Linq to SQL Model verification

    Models public class Student { public int Id { get; set; } [Required(ErrorMessage = "姓名不能为空!&quo ...

随机推荐

  1. ASP.NET MVC5+EF6+EasyUI 后台管理系统(75)-微信公众平台开发-用户管理

    系列目录 前言 本节主要是关注者(即用户)和用户组的管理,微信公众号提供了用户和用户组的管理,我们可以在微信公众号官方里面进行操作,添加备注和标签,以及移动用户组别,同时,微信公众号也提供了相应的接口 ...

  2. C++随笔:.NET CoreCLR之GC探索(2)

    首先谢谢 @dudu 和 @张善友 这2位大神能订阅我,本来在写这个系列以前,我一直对写一些核心而且底层的知识持怀疑态度,我为什么持怀疑态度呢?因为一般写高层语言的人99%都不会碰底层,其实说句实话, ...

  3. [转载]Cookie/Session的机制与安全

    Cookie和Session是为了在无状态的HTTP协议之上维护会话状态,使得服务器可以知道当前是和哪个客户在打交道.本文来详细讨论Cookie和Session的实现机制,以及其中涉及的安全问题. 因 ...

  4. JavaWeb——Listener

    一.基本概念 JavaWeb里面的listener是通过观察者设计模式进行实现的.对于观察者模式,这里不做过多介绍,大概讲一下什么意思. 观察者模式又叫发布订阅模式或者监听器模式.在该模式中有两个角色 ...

  5. 如何编译Zookeeper源码

    1. 安装Ant Ant下载地址:http://ant.apache.org/bindownload.cgi 解压即可. 2. 下载Zookeeper源码包 https://github.com/ap ...

  6. 分布式存储 FastDFS-5.0.5线上搭建

    前言:       由于公司项目需要,最近开始学习一下分布式存储相关知识,确定使用FastDFS这个开源工具.学习之初,自己利用VMware虚拟机搭建了一个5台机器的集群,摸清了安装过程中可能出现的问 ...

  7. 迟来的Json反序列化

    源码发布 搞了一个下午,终于搞定了这个号称中国的github...以后源码直接在这里发布了(github实在用不来,英文实在太烂了) https://code.csdn.net/jy02305022/ ...

  8. Android-Drawable、Bitmap、byte[]、资源文件相互转换

    我们在Android的开发中,经常可以遇到图片的处理,当中,有很多是 Bitmap.Drawable.byte[]和资源文件它们直接相互转换. 今天就此总结一下: 1.资源文件转为Drawable 2 ...

  9. Laravel 5.3 登录注册底层实现详解

          每个控制器都使用 trait 来引入它们需要的方法 */ 用于处理用户登录认证 用于处理新用户注册 包含重置密码逻辑 用于处理重置密码邮件链接   认证需要的视图 包含了应用的基础布局文件 ...

  10. 解析大型.NET ERP系统 多国语言实现

    实现多国语言有许多种实现方案,无外乎是一种字符串替换技术,将界面控件的文本标签替换成相应语言的文字..NET Windows Forms实现多国语言的方法有以下几种: 1 .NET的方案,使用资源文件 ...