NpgsqlHelper.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using Npgsql;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using WWPipeLine.Commons;
  9. namespace WWPipeLine.MapBasic
  10. {
  11. public class NpgsqlHelper
  12. {
  13. public NpgsqlHelper() { }
  14. public static string ConStr = ComsStatic.ConfigsNpgsql;
  15. public int ExecuteNonQuery(string sql)
  16. {
  17. int result = -1;
  18. using (NpgsqlConnection connection = new NpgsqlConnection(ConStr))
  19. {
  20. using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
  21. {
  22. try
  23. {
  24. connection.Open();
  25. result = command.ExecuteNonQuery();
  26. }
  27. catch (NpgsqlException exception)
  28. {
  29. LogHelper.Error(string.Format("执行SQL[{0}]出错,详细信息为:{1}", sql, exception.Message));
  30. }
  31. finally
  32. {
  33. connection.Close();
  34. }
  35. }
  36. }
  37. return result;
  38. }
  39. public object ExecuteScalar(string sql)
  40. {
  41. object obj = null;
  42. using (NpgsqlConnection connection = new NpgsqlConnection(ConStr))
  43. {
  44. using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
  45. {
  46. try
  47. {
  48. connection.Open();
  49. obj = command.ExecuteScalar();
  50. }
  51. catch (NpgsqlException exception)
  52. {
  53. obj = -1;
  54. LogHelper.Error(string.Format("执行SQL[{0}]出错,详细信息为:{1}", sql, exception.Message));
  55. }
  56. finally
  57. {
  58. connection.Close();
  59. }
  60. }
  61. }
  62. return obj;
  63. }
  64. public DataSet ExecuteQuery(string sql)
  65. {
  66. DataSet result = new DataSet();
  67. using (NpgsqlConnection connection = new NpgsqlConnection(ConStr))
  68. {
  69. using (NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(sql, connection))
  70. {
  71. try
  72. {
  73. connection.Open();
  74. dataAdapter.Fill(result);
  75. }
  76. catch (NpgsqlException exception)
  77. {
  78. LogHelper.Error(string.Format("执行SQL【{0}】出错,详细信息为:{1}", sql, exception.Message));
  79. }
  80. finally
  81. {
  82. connection.Close();
  83. }
  84. }
  85. }
  86. return result;
  87. }
  88. }
  89. }