PostgresqlDB.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 (var connection = new NpgsqlConnection(_connectionString))
  86. {
  87. connection.Open();
  88. connection.ChangeDatabase(_dbName);
  89. using (NpgsqlCommand command = new NpgsqlCommand())
  90. {
  91. try
  92. {
  93. PrepareCommand(command, connection, cmdText, p);
  94. NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
  95. da.Fill(ds);
  96. }
  97. catch (Exception ex)
  98. {
  99. LOG.Error("执行查询出错," + cmdText, ex);
  100. }
  101. }
  102. }
  103. return ds;
  104. }
  105. catch(Exception ex)
  106. {
  107. LOG.Error("执行查询出错,"+cmdText, ex);
  108. }
  109. return null;
  110. }
  111. public NpgsqlDataReader ExecuteReader(string cmdText, params object[] p)
  112. {
  113. try
  114. {
  115. using (NpgsqlCommand command = new NpgsqlCommand())
  116. {
  117. PrepareCommand(command, _conn, cmdText, p);
  118. return command.ExecuteReader(CommandBehavior.CloseConnection);
  119. }
  120. }
  121. catch
  122. {
  123. Close();
  124. throw;
  125. }
  126. }
  127. public bool ActiveConnection()
  128. {
  129. if (_conn!=null && _conn.State == ConnectionState.Open)
  130. return true;
  131. return Open();
  132. }
  133. public void Close()
  134. {
  135. try
  136. {
  137. if (_conn != null)
  138. _conn.Close();
  139. _conn = null;
  140. }
  141. catch (Exception ex)
  142. {
  143. LOG.Write(ex);
  144. }
  145. }
  146. public void CreateDBIfNotExisted(string db)
  147. {
  148. NpgsqlDataReader reader = ExecuteReader(string.Format(@"select datname from pg_catalog.pg_database where datname='{0}'", db));
  149. if (!reader.HasRows)
  150. {
  151. string sql = string.Format(@"
  152. CREATE DATABASE {0}
  153. WITH OWNER = postgres
  154. ENCODING = 'UTF8'
  155. TABLESPACE = pg_default
  156. CONNECTION LIMIT = -1", db);
  157. ExecuteNonQuery(sql);
  158. }
  159. try
  160. {
  161. _conn.ChangeDatabase(db);
  162. }
  163. catch
  164. {
  165. _conn.Close();
  166. throw;
  167. }
  168. }
  169. public void CreateTableIfNotExisted(string table, Dictionary<string, Type> columns, bool addPID, string primaryKey)
  170. {
  171. NpgsqlDataReader reader = ExecuteReader(string.Format(@"select column_name from information_schema.columns where table_name = '{0}'", table));
  172. if (!reader.HasRows)
  173. {
  174. string cols = addPID ? " \"PID\" serial NOT NULL," : "";
  175. foreach (var item in columns)
  176. {
  177. if (item.Value == typeof(int))
  178. cols += string.Format("\"{0}\" integer,", item.Key);
  179. else if (item.Value == typeof(string))
  180. cols += string.Format("\"{0}\" text,", item.Key);
  181. else if (item.Value == typeof(DateTime))
  182. cols += string.Format("\"{0}\" timestamp without time zone,", item.Key);
  183. else if (item.Value == typeof(bool))
  184. cols += string.Format("\"{0}\" boolean,", item.Key);
  185. }
  186. if (string.IsNullOrEmpty(primaryKey))
  187. {
  188. if (cols.LastIndexOf(',') == cols.Length-1)
  189. cols = cols.Remove(cols.Length - 1);
  190. }else
  191. {
  192. cols += string.Format("CONSTRAINT \"{0}_pkey\" PRIMARY KEY (\"{1}\" )", table, primaryKey);
  193. }
  194. ExecuteNonQuery(string.Format("CREATE TABLE \"{0}\"({1})WITH ( OIDS=FALSE );", table, cols));
  195. }
  196. }
  197. }
  198. }