create_data_tbl.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import time
  2. import traceback
  3. import pymysql
  4. class Mysql:
  5. def __init__(self, host='', user='', passwd='', db='', port=3306, charset='utf8'):
  6. self.host = host
  7. self.user = user
  8. self.passwd = passwd
  9. self.db = db
  10. self.port = port
  11. self.charset = charset
  12. self.conn = None
  13. self.cursor = None
  14. self._conn()
  15. def _conn(self):
  16. try:
  17. self.conn = pymysql.connect(host=self.host, user=self.user, password=self.passwd, db=self.db, port=self.port)
  18. self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
  19. return True
  20. except Exception as e:
  21. print(e)
  22. return False
  23. def run(self):
  24. self.create_data_table()
  25. def get_stations_info(self):
  26. sql = "SELECT * FROM station_info_tbl WHERE status = 1;"
  27. self.cursor.execute(sql)
  28. results = self.cursor.fetchall()
  29. return results
  30. def get_device_by_station_name(self, station_name):
  31. sql = "select DISTINCT (device_name) from data_point_tbl where station_name = '%s'" % station_name
  32. self.cursor.execute(sql)
  33. results = self.cursor.fetchall()
  34. return results
  35. def get_point_by_device_name(self, device_name):
  36. sql = "SELECT * FROM data_point_tbl WHERE device_name = '%s'" % device_name
  37. self.cursor.execute(sql)
  38. results = self.cursor.fetchall()
  39. return results
  40. def create_data_table(self):
  41. stations_list = self.get_stations_info()
  42. for each_station in stations_list:
  43. devices_list = self.get_device_by_station_name(each_station['station_name'])
  44. for each_device in devices_list:
  45. points_list = self.get_point_by_device_name(each_device['device_name'])
  46. print(points_list)
  47. print("------------")
  48. table_name = 'table_' + each_device['device_name']
  49. sql_c = "CREATE TABLE IF NOT EXISTS %s (id bigint primary key , times datetime NOT NULL,INDEX (times)) ENGINE=InnoDB DEFAULT CHARSET=utf8;" % table_name
  50. self.cursor.execute(sql_c)
  51. for i in points_list:
  52. dataType = i['storage_type']
  53. columnName = "c" + str(i['serial_number'])
  54. sql_add = "ALTER TABLE %s ADD %s %s comment '%s'" % (table_name, columnName, dataType, i['io_point_name'])
  55. print(f"sql_add: {sql_add}")
  56. self.cursor.execute(sql_add)
  57. print(table_name, "done !")
  58. if __name__ == '__main__':
  59. Mysql(host='127.0.0.1', user='root', passwd='zzZZ4144670..', db='shucai').run()