YDSPHepler.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using Microsoft.Extensions.Configuration;
  8. using System.IO;
  9. namespace YDSP.Core
  10. {
  11. /// <summary>
  12. /// 帮助类
  13. /// </summary>
  14. public class YDSPHepler
  15. {
  16. private static readonly object obj = new object();
  17. private static YDSPHepler instance = null;
  18. public IConfigurationRoot Config { get; }
  19. private YDSPHepler()
  20. {
  21. var builder = new ConfigurationBuilder()
  22. .SetBasePath(Directory.GetCurrentDirectory())
  23. .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
  24. Config = builder.Build();
  25. }
  26. public static YDSPHepler GetInstance()
  27. {
  28. if (instance == null)
  29. {
  30. lock (obj)
  31. {
  32. if (instance == null)
  33. {
  34. instance = new YDSPHepler();
  35. }
  36. }
  37. }
  38. return instance;
  39. }
  40. public static string GetConfig(string name)
  41. {
  42. return GetInstance().Config.GetSection(name).Value;
  43. }
  44. private static string CONNECTION_STRING = YDSPHepler.GetConfig("ConnectionStrings:DefaultConnection");
  45. private static string _conStr = CONNECTION_STRING;
  46. private static SqlConnection _ion;
  47. public static SqlConnection _Ion
  48. {
  49. get
  50. {
  51. if (_ion == null)
  52. _ion = new SqlConnection(_conStr);
  53. if (_ion.State != ConnectionState.Open)
  54. _ion.Open();
  55. return _ion;
  56. }
  57. }
  58. /// <summary>
  59. /// 执行数据库增删改
  60. /// </summary>
  61. /// <param name="sql">执行的语句</param>
  62. /// <returns></returns>
  63. public static int ExecuteNonQuery(string sql)
  64. {
  65. SqlCommand and = _Ion.CreateCommand();
  66. and.CommandText = sql;
  67. try
  68. {
  69. return and.ExecuteNonQuery();
  70. }
  71. catch (Exception ex)
  72. {
  73. Console.WriteLine(ex.Message);
  74. return 0;
  75. }
  76. finally
  77. {
  78. and.Connection.Close();
  79. }
  80. }
  81. /// <summary>
  82. /// 负责查询数据库数据
  83. /// </summary>
  84. /// <param name="sql"></param>
  85. /// <returns></returns>
  86. public static DataTable GetData(string sql)
  87. {
  88. SqlDataAdapter adapter = new SqlDataAdapter(sql, _conStr);
  89. DataSet set = new DataSet();
  90. adapter.Fill(set);
  91. return set.Tables[0];
  92. }
  93. public static DataSet GetSet(string sql)
  94. {
  95. SqlDataAdapter adapter = new SqlDataAdapter(sql, _conStr);
  96. DataSet set = new DataSet();
  97. adapter.Fill(set);
  98. return set;
  99. }
  100. }
  101. }