databasethread.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #include "databasethread.h"
  2. #define HostName "172.17.35.51"
  3. //#define HostName "124.71.140.20"
  4. #define HostPort 3306
  5. #define UserName "usky"
  6. #define PassWord "Yt#75Usky"
  7. #define DatabaseName "usky-park"
  8. DatabaseThread::DatabaseThread(QObject *parent) : QThread(parent)
  9. {
  10. hour = 255;
  11. keep=false;
  12. sqlList.clear();
  13. alarmList.clear();
  14. db = QSqlDatabase::addDatabase("QMYSQL","write_db");
  15. db.setHostName(QString(HostName));
  16. db.setPort(HostPort);
  17. db.setUserName(QString(UserName));
  18. db.setPassword(QString(PassWord));
  19. db.setDatabaseName(QString(DatabaseName));
  20. }
  21. void DatabaseThread::appendSql(QString sql)
  22. {
  23. sqlList.append(sql);
  24. }
  25. void DatabaseThread::appendAlarm(QString sql)
  26. {
  27. alarmList.append(sql);
  28. }
  29. void DatabaseThread::stop()
  30. {
  31. keep = false;
  32. }
  33. void DatabaseThread::run()
  34. {
  35. if(!db.open()){
  36. emit dbdata_log(QString("[%1] writeProcess DatabaseThread db open failed").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")));
  37. }else{
  38. QString ip,port,username,password;
  39. QSqlQuery mqttqry = db.exec(QString("select mqtt_ip,mqtt_port,username,passwd from yt_mqtt where item_name = 'data-write'"));
  40. while (mqttqry.next()) {
  41. ip = mqttqry.value(0).toString();
  42. port = mqttqry.value(1).toString();
  43. username = mqttqry.value(2).toString();
  44. password = mqttqry.value(3).toString();
  45. }
  46. mqttqry.clear();
  47. emit dbdata_log(QString("mqttinfo %1 %2 %3 %4").arg(ip).arg(port).arg(username).arg(password));
  48. emit mqtt_conf(ip,port,username,password);
  49. db.close();
  50. }
  51. keep = true;
  52. while (keep) {
  53. if(!db.open()){
  54. db.open();
  55. }else{
  56. if(sqlList.length()>0){
  57. while (sqlList.length()>0) {
  58. db.exec(sqlList.first());
  59. emit dbdata_log(QString("[%1] sqlList.length() %2 writeProcess sql %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")).arg(sqlList.length()).arg(sqlList.first()));
  60. sqlList.removeFirst();
  61. usleep(1000);
  62. }
  63. }
  64. if(alarmList.length()>0){
  65. while (alarmList.length()>0) {
  66. db.exec(alarmList.first());
  67. emit dbdata_log(QString("[%1] writeProcess alarm sql %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")).arg(alarmList.first()));
  68. alarmList.removeFirst();
  69. usleep(1000);
  70. }
  71. }
  72. }
  73. usleep(50000);
  74. }
  75. }