Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. #! /usr/bin/env python3.5
  2.  
  3. # import standard libraries
  4. import os
  5. import csv
  6. from datetime import datetime
  7. # import additional libraries
  8. import mysql.connector # import library mysql.connector
  9. from mysql.connector import errorcode # import library errorcod from mysql.conn
  10.  
  11. # db configuration
  12. DB_CONFIG = dict(
  13. user='root',
  14. password='t00r0DGn1',
  15. host='localhost',
  16. database='odgn'
  17. )
  18. # range id of sensors(1 - 34)
  19. SENSOR_IDS = range(23, 45)
  20.  
  21. try:
  22. cnx = mysql.connector.connect(**DB_CONFIG) # open connection to the MySQL server and store the conn object in the variable cnx
  23.  
  24. except mysql.connector.Error as err:
  25. if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
  26. raise Exception("Something is wrong with your user name or password")
  27.  
  28. elif err.errno == errorcode.ER_BAD_DB_ERROR:
  29. raise Exception("Database does not exist")
  30.  
  31. else:
  32. raise Exception(err)
  33.  
  34. cursor = cnx.cursor() #create a new cursor
  35.  
  36. for sensor_id in SENSOR_IDS:
  37.  
  38. filename = 'file_sensor_%s.csv' % sensor_id
  39. # быстрый способ чтения последней строки файла в байтовой строке, как работает - хз, взял с форума
  40. with open(filename, 'rb') as f:
  41. f.seek(-min(os.path.getsize('file_sensor_23.csv'),200),2)
  42. txt = ((f.read().splitlines()[-1]).decode('utf-8')).split(';') # get a string and split it into an array
  43. dt = datetime.strptime(txt[0], "%d.%m.%Y %H:%M") # formating date to MySQL datetime format
  44.  
  45. query = "SELECT date_format(date, '%d.%m.%Y %H:%i') as date, sensor, id, h FROM data_hydrolevel WHERE sensor = '%s' AND date_format(date, '%Y-%m-%d %H:%i') > %s;"
  46. cursor.execute(query, (sensor_id, dt))
  47.  
  48. with open(filename, 'a') as f:
  49. writer = csv.writer(f, delimiter=';')
  50. writer.writerows(cursor)
  51.  
  52. cursor.close()
  53.  
  54. cnx.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement