DatabaseManager.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Aitex.Core.Util;
  6. using Aitex.Core.Utilities;
  7. using Aitex.Core.RT.Event;
  8. using Aitex.Core.RT.Log;
  9. using System.Data;
  10. using System.IO;
  11. using Aitex.Core.RT.OperationCenter;
  12. using MECF.Framework.Common.DBCore;
  13. namespace Aitex.Core.RT.DBCore
  14. {
  15. public class DatabaseManager : ICommonDB
  16. {
  17. PeriodicJob _thread;
  18. FixSizeQueue<string> _sqlQueue = new FixSizeQueue<string>(1000);
  19. PostgresqlDB _db = new PostgresqlDB();
  20. DatabaseCleaner _cleaner = new DatabaseCleaner();
  21. public void Initialize(string connectionString, string dbName, string sqlFile)
  22. {
  23. if (string.IsNullOrEmpty(connectionString))
  24. {
  25. throw new ApplicationException("数据库连接字段未设置");
  26. }
  27. PostgresqlHelper.ConnectionString = connectionString;
  28. if (!_db.Open(connectionString, dbName))
  29. {
  30. LOG.Error("数据库连接失败");
  31. }
  32. else
  33. {
  34. PrepareDatabaseTable(sqlFile);
  35. }
  36. _cleaner.Initialize(dbName);
  37. _thread = new PeriodicJob(100, this.PeriodicRun, "DBJob", true);
  38. DB.Instance = this;
  39. }
  40. public void Terminate()
  41. {
  42. if (_thread != null)
  43. {
  44. _thread.Stop();
  45. _thread = null;
  46. }
  47. _cleaner.Terminate();
  48. _db.Close();
  49. }
  50. bool PeriodicRun()
  51. {
  52. if (!_db.ActiveConnection())
  53. return true;
  54. string sql;
  55. while (_sqlQueue.TryDequeue(out sql))
  56. {
  57. try
  58. {
  59. _db.ExecuteNonQuery(sql);
  60. }
  61. catch (Exception ex)
  62. {
  63. LOG.Error(string.Format("执行数据库操作错误, {0}, {1}", ex.Message, sql));
  64. }
  65. }
  66. return true;
  67. }
  68. public void Insert(string sql)
  69. {
  70. _sqlQueue.Enqueue(sql);
  71. }
  72. public void CreateTableIfNotExisted(string table, Dictionary<string, Type> columns, bool addPID, string primaryKey)
  73. {
  74. _db.CreateTableIfNotExisted(table, columns, addPID, primaryKey);
  75. }
  76. public DataSet ExecuteDataset(string cmdText, params object[] p)
  77. {
  78. return _db.ExecuteDataset(cmdText, p);
  79. }
  80. void PrepareDatabaseTable(string sqlFile)
  81. {
  82. if (string.IsNullOrEmpty(sqlFile) || !File.Exists(sqlFile))
  83. {
  84. LOG.Info("没有更新Sql数据库,文件:" + sqlFile);
  85. return;
  86. }
  87. try
  88. {
  89. using (StreamReader fs = new System.IO.StreamReader(sqlFile))
  90. {
  91. string sql = fs.ReadToEnd();
  92. _db.ExecuteNonQuery(sql);
  93. LOG.Write("完成对数据库表格的更新操作");
  94. }
  95. }
  96. catch (Exception ex)
  97. {
  98. LOG.Write(ex);
  99. }
  100. }
  101. }
  102. }