DBDataProvider.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using sql_pagining.models;
  7. using Dapper;
  8. using MySqlConnector;
  9. namespace sql_pagining.models
  10. {
  11. internal class DBDataProvider : IDataProvider
  12. {
  13. private string searchFilter = "";
  14. private Dictionary<string, object> filters = new Dictionary<string, object>();
  15. private string orderCondition = "";
  16. static string connectionString = "Server=kolei.ru; User ID=sbahtina; Password=010906; Database=sbahtina";
  17. public IEnumerable<Product> getProduct(int pageNum)
  18. {
  19. using (MySqlConnection db = new MySqlConnection(connectionString))
  20. {
  21. var builder = new SqlBuilder();
  22. if (orderCondition.Length > 0)
  23. builder.OrderBy(orderCondition);
  24. if (filters.Count > 0)
  25. {
  26. foreach (var item in filters)
  27. builder.Where(item.Key, item.Value);
  28. }
  29. var template = builder.AddTemplate(
  30. "SELECT * FROM ProductView /**where**/ /**orderby**/ LIMIT @pageLen OFFSET @offset",
  31. new { pageLen = Globals.PAGE_LEN, offset = (pageNum - 1) * Globals.PAGE_LEN }
  32. );
  33. return db.Query<Product>(
  34. template.RawSql,
  35. template.Parameters).ToList();
  36. }
  37. }
  38. public int getProductCount()
  39. {
  40. using (MySqlConnection db = new MySqlConnection(connectionString))
  41. {
  42. var builder = new SqlBuilder();
  43. if (filters.Count > 0)
  44. {
  45. foreach (var item in filters)
  46. {
  47. builder.Where(item.Key, item.Value);
  48. }
  49. }
  50. var template = builder.AddTemplate(
  51. "SELECT count(*) FROM ProductView /**where**/");
  52. return db.QuerySingle<int>(
  53. template.RawSql,
  54. template.Parameters);
  55. }
  56. }
  57. public void setOrder(string condition)
  58. {
  59. orderCondition = condition;
  60. }
  61. public void addFilter(string name, object value)
  62. {
  63. filters.Add(name, value);
  64. }
  65. public void clearFilter()
  66. {
  67. filters.Clear();
  68. }
  69. public IEnumerable<ProductType> getProductTypes()
  70. {
  71. using (MySqlConnection db = new MySqlConnection(connectionString))
  72. {
  73. return db.Query<ProductType>("SELECT * FROM ProductType");
  74. }
  75. }
  76. }
  77. }