NpgsqlHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. private static string ConStr = IniHelper.Read(IniHelper.KEY_ConfigsNpgsql_PATH);
  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. LogHelper.Error(string.Format("执行SQL[{0}]出错,详细信息为:{1}", sql, exception.Message));
  54. }
  55. finally
  56. {
  57. connection.Close();
  58. }
  59. }
  60. }
  61. return obj;
  62. }
  63. public DataSet ExecuteQuery(string sql)
  64. {
  65. DataSet result = new DataSet();
  66. using (NpgsqlConnection connection = new NpgsqlConnection(ConStr))
  67. {
  68. using (NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(sql, connection))
  69. {
  70. try
  71. {
  72. connection.Open();
  73. dataAdapter.Fill(result);
  74. }
  75. catch (NpgsqlException exception)
  76. {
  77. LogHelper.Error(string.Format("执行SQL【{0}】出错,详细信息为:{1}", sql, exception.Message));
  78. }
  79. finally
  80. {
  81. connection.Close();
  82. }
  83. }
  84. }
  85. return result;
  86. }
  87. }
  88. }