DatabaseManager.cs 3.0 KB

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