PostgresqlDB.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Npgsql;
  6. using Aitex.Core.RT.Log;
  7. using System.Data;
  8. using Aitex.Core.Utilities;
  9. namespace Aitex.Core.RT.DBCore
  10. {
  11. public class PostgresqlDB
  12. {
  13. NpgsqlConnection _conn;
  14. string _connectionString;
  15. string _dbName;
  16. Retry _retryConnection = new Retry();
  17. public PostgresqlDB()
  18. {
  19. }
  20. public bool Open(string connectionString, string dbName)
  21. {
  22. _connectionString = connectionString;
  23. _dbName = dbName;
  24. bool result = true;
  25. try
  26. {
  27. if (_conn != null)
  28. _conn.Close();
  29. _conn = new NpgsqlConnection(connectionString);
  30. _conn.Open();
  31. if (!string.IsNullOrEmpty(dbName))
  32. CreateDBIfNotExisted(dbName);
  33. }
  34. catch (Exception ex)
  35. {
  36. if (_conn != null)
  37. {
  38. _conn.Close();
  39. _conn = null;
  40. }
  41. result = false;
  42. LOG.Write(ex);
  43. }
  44. _retryConnection.Result = result;
  45. //if (_retryConnection.IsErrored)
  46. return result;
  47. }
  48. bool Open()
  49. {
  50. return Open(_connectionString, _dbName);
  51. }
  52. void PrepareCommand(NpgsqlCommand cmd, NpgsqlConnection conn, string cmdText, params object[] p)
  53. {
  54. cmd.Parameters.Clear();
  55. cmd.Connection = conn;
  56. cmd.CommandText = cmdText;
  57. cmd.CommandType = CommandType.Text;
  58. if (p != null)
  59. {
  60. foreach (object parm in p)
  61. cmd.Parameters.AddWithValue(string.Empty, parm);
  62. }
  63. }
  64. public int ExecuteNonQuery(string cmdText, params object[] p)
  65. {
  66. try
  67. {
  68. using (NpgsqlCommand command = new NpgsqlCommand())
  69. {
  70. PrepareCommand(command, _conn, cmdText, p);
  71. return command.ExecuteNonQuery();
  72. }
  73. }
  74. catch
  75. {
  76. Close();
  77. throw;
  78. }
  79. }
  80. public DataSet ExecuteDataset(string cmdText, params object[] p)
  81. {
  82. try
  83. {
  84. DataSet ds = new DataSet();
  85. using (NpgsqlCommand command = new NpgsqlCommand())
  86. {
  87. PrepareCommand(command, _conn, cmdText, p);
  88. NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
  89. da.Fill(ds);
  90. }
  91. return ds;
  92. }
  93. catch(Exception ex)
  94. {
  95. LOG.Error("执行查询出错,"+cmdText, ex);
  96. }
  97. return null;
  98. }
  99. public NpgsqlDataReader ExecuteReader(string cmdText, params object[] p)
  100. {
  101. try
  102. {
  103. using (NpgsqlCommand command = new NpgsqlCommand())
  104. {
  105. PrepareCommand(command, _conn, cmdText, p);
  106. return command.ExecuteReader(CommandBehavior.CloseConnection);
  107. }
  108. }
  109. catch
  110. {
  111. Close();
  112. throw;
  113. }
  114. }
  115. public bool ActiveConnection()
  116. {
  117. if (_conn!=null && _conn.State == ConnectionState.Open)
  118. return true;
  119. return Open();
  120. }
  121. public void Close()
  122. {
  123. try
  124. {
  125. if (_conn != null)
  126. _conn.Close();
  127. _conn = null;
  128. }
  129. catch (Exception ex)
  130. {
  131. LOG.Write(ex);
  132. }
  133. }
  134. public void CreateDBIfNotExisted(string db)
  135. {
  136. NpgsqlDataReader reader = ExecuteReader(string.Format(@"select datname from pg_catalog.pg_database where datname='{0}'", db));
  137. if (!reader.HasRows)
  138. {
  139. string sql = string.Format(@"
  140. CREATE DATABASE {0}
  141. WITH OWNER = postgres
  142. ENCODING = 'UTF8'
  143. TABLESPACE = pg_default
  144. CONNECTION LIMIT = -1", db);
  145. ExecuteNonQuery(sql);
  146. }
  147. try
  148. {
  149. _conn.ChangeDatabase(db);
  150. }
  151. catch
  152. {
  153. _conn.Close();
  154. throw;
  155. }
  156. }
  157. public void CreateTableIfNotExisted(string table, Dictionary<string, Type> columns, bool addPID, string primaryKey)
  158. {
  159. NpgsqlDataReader reader = ExecuteReader(string.Format(@"select column_name from information_schema.columns where table_name = '{0}'", table));
  160. if (!reader.HasRows)
  161. {
  162. string cols = addPID ? " \"PID\" serial NOT NULL," : "";
  163. foreach (var item in columns)
  164. {
  165. if (item.Value == typeof(int))
  166. cols += string.Format("\"{0}\" integer,", item.Key);
  167. else if (item.Value == typeof(string))
  168. cols += string.Format("\"{0}\" text,", item.Key);
  169. else if (item.Value == typeof(DateTime))
  170. cols += string.Format("\"{0}\" timestamp without time zone,", item.Key);
  171. else if (item.Value == typeof(bool))
  172. cols += string.Format("\"{0}\" boolean,", item.Key);
  173. }
  174. if (string.IsNullOrEmpty(primaryKey))
  175. {
  176. if (cols.LastIndexOf(',') == cols.Length-1)
  177. cols = cols.Remove(cols.Length - 1);
  178. }else
  179. {
  180. cols += string.Format("CONSTRAINT \"{0}_pkey\" PRIMARY KEY (\"{1}\" )", table, primaryKey);
  181. }
  182. ExecuteNonQuery(string.Format("CREATE TABLE \"{0}\"({1})WITH ( OIDS=FALSE );", table, cols));
  183. }
  184. }
  185. }
  186. }