MicrosoftSQLClient.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace PRSDesktop;
  9. public abstract class MicrosoftSQLClient : IDisposable
  10. {
  11. private SqlConnection? connection;
  12. protected abstract string GetConnectionString();
  13. public bool Connect()
  14. {
  15. connection = new SqlConnection(GetConnectionString());
  16. try
  17. {
  18. connection.Open();
  19. }
  20. catch (Exception e)
  21. {
  22. connection = null;
  23. }
  24. return IsConnected;
  25. }
  26. public bool IsConnected => connection != null;
  27. public void Disconnect()
  28. {
  29. if (connection != null)
  30. {
  31. connection.Dispose();
  32. connection = null;
  33. }
  34. }
  35. public DataTable Query(string sql, string tablename, SqlParameter[]? parameters = null)
  36. {
  37. var result = new DataTable(tablename);
  38. if (connection != null)
  39. {
  40. using (var _command = new SqlCommand(sql.Replace("\r\n"," ").Replace("\n"," ").Replace("\r"," "), connection))
  41. {
  42. if (parameters is not null)
  43. {
  44. foreach (var _parameter in parameters)
  45. _command.Parameters.Add(_parameter);
  46. }
  47. using var _adapter = new SqlDataAdapter(_command);
  48. _adapter.Fill(result);
  49. }
  50. connection.Close();
  51. }
  52. return result;
  53. }
  54. public int ExecuteSQL(string sql, SqlParameter[]? parameters = null)
  55. {
  56. int result = 0;
  57. if(connection != null)
  58. {
  59. using(var command = new SqlCommand(sql.Replace("\r\n"," ").Replace("\n", " ").Replace("\r"," "), connection))
  60. {
  61. if (parameters is not null)
  62. {
  63. foreach (var _parameter in parameters)
  64. command.Parameters.Add(_parameter);
  65. }
  66. result = command.ExecuteNonQuery();
  67. }
  68. connection.Close();
  69. }
  70. return result;
  71. }
  72. public static int GetInteger(DataRow row, string field, int defaultvalue = 0)
  73. {
  74. return row[field] == DBNull.Value ? 0 : Convert.ToInt32(row[field]);
  75. }
  76. public static double GetDouble(DataRow row, string field, double defaultvalue = 0.0)
  77. {
  78. return row[field] == DBNull.Value
  79. ? 0.0
  80. : Convert.ToDouble(row[field]);
  81. }
  82. public static string GetString(DataRow row, string field, string defaultvalue = "")
  83. {
  84. return row[field] == DBNull.Value ? "" : row[field] as string ?? defaultvalue;
  85. }
  86. public static byte[] GetBinary(DataRow row, string field)
  87. {
  88. return row[field] == DBNull.Value ? [] : (byte[])row[field];
  89. }
  90. public void Dispose()
  91. {
  92. Disconnect();
  93. }
  94. }