// it's for Latex

pages

[How to connect Python programs to MariaDB in NAS] #12. Upload every data in folder to database

이제 정말 모든 작업이 끝나고 막바지 단계이다.

필자가 사용하고 있는 센서는 데이터 값을 text file 형식으로 지정된 folder에 초 단위로 저장한다. 파일 명은 date_time (날짜 및 시간) 이다.

그래서 필자는 (1) 폴더안의 파일 리스트를 확인 후 (2) 이름 순으로 정렬시키고 (3) 가장 빠른 파일에 대해 parsing 후 DB에 업로드를 한 후 (4) 해당 파일은 삭제
할 것이다. 이렇게 함으로써 센서로부터 전달받는 모든 데이터를 DB에 업로드 가능하게 된다.


작업환경
- OS : Windows 10
- PC : LattePanda 4G RAM 64G eMMC (DFR0419)
- NAS : DS1618+
- Python : 3.6.8
- Tool : Pycharm
- PC와 NAS는 다른 네트워크
- PC와 NAS는 각각 Internet이 가능한 상태



바로 소스를 보겠다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/python
import mysql.connector as mariadb
from mysql.connector import Error
import pandas as pd
import os

try:
   connection = mariadb.connect(host='#07의 2번에서 확인한 NAS DDNS의 외부주소',
                                user='#06의 3번에서 확인한 user 명 입력',
                                port='#06의 6번에서 확인된 Port 번호 입력',
                                password='#06의 3번에서 login에 사용되는 password 입력',
                                database='#06의 4번에서 확인된 db 명 입력')

   if connection.is_connected():
       db_Info = connection.get_server_info()
       print("Connected to MySQL database... MySQL Server version on ", db_Info)

       cursor = connection.cursor(prepared=True)
       cursor.execute("select database()")
       record = cursor.fetchone()
       print("Your connected to -", record)

       # reset primary Auto Increment to 1
       A_I_reset_query = """ALTER TABLE data_sensor AUTO_INCREMENT=1"""
       cursor.execute(A_I_reset_query)

       path_dir = 'C:\Data'
       while (1) :
           # if there is no file in the directory, then do nothing
           file_list = os.listdir(path_dir)
           if len(file_list) > 0:
               file_list.sort()
               location = path_dir+'\\'+file_list[0]
               print(location)

               df = pd.read_csv(location,
                                skiprows=1,
                                skipfooter=1027,
                                sep='\t')
               #print(df)
               date_time = df.iloc[0,0]
               time_rms = df.iloc[0,5]
               time_peak = df.iloc[04]
               time_crest_factor = df.iloc[06]
               frequency_peak_1 = df.iloc[08]
               frequency_peak_2 = df.iloc[010]
               frequency_peak_3 = df.iloc[012]
               frequency_peak_4 = df.iloc[014]
               frequency_peak_5 = df.iloc[016]
               frequency_peak_6 = df.iloc[018]
               frequency_band_1 = df.iloc[09]
               frequency_band_2 = df.iloc[011]
               frequency_band_3 = df.iloc[013]
               frequency_band_4 = df.iloc[015]
               frequency_band_5 = df.iloc[017]
               frequency_band_6 = df.iloc[019]
               '''
               print("date_time : ", date_time)
               print("time_rms : ", time_rms)
               print("time_peak : ", time_peak)
               print("time_crest_factor : ", time_crest_factor)
               print("frequency_peak_1 : ", frequency_peak_1)
               print("frequency_peak_2 : ", frequency_peak_2)
               print("frequency_peak_3 : ", frequency_peak_3)
               print("frequency_peak_4 : ", frequency_peak_4)
               print("frequency_peak_5 : ", frequency_peak_5)
               print("frequency_peak_6 : ", frequency_peak_6)
               print("frequency_band_1 : ", frequency_band_1)
               print("frequency_band_2 : ", frequency_band_2)
               print("frequency_band_3 : ", frequency_band_3)
               print("frequency_band_4 : ", frequency_band_4)
               print("frequency_band_5 : ", frequency_band_5)
               print("frequency_band_6 : ", frequency_band_6)
               '''
               sql_insert_query = """ INSERT INTO `data_sensor`
                                         (`date_time`, `time_rms`, `time_peak`, `time_crest_factor`, 
                                         `frequency_peak_1`, `frequency_peak_2`, `frequency_peak_3`, 
                                         `frequency_peak_4`, `frequency_peak_5`, `frequency_peak_6`,
                                         `frequency_band_1`, `frequency_band_2`, `frequency_band_3`,
                                         `frequency_band_4`, `frequency_band_5`, `frequency_band_6`) 
                                         VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
               insert_tuple = (date_time,time_rms,time_peak,time_crest_factor,
                               frequency_peak_1,frequency_peak_2,frequency_peak_3,
                               frequency_peak_4,frequency_peak_5,frequency_peak_6,
                               frequency_band_1,frequency_band_2,frequency_band_3,
                               frequency_band_4,frequency_band_5,frequency_band_6)
               result = cursor.execute(sql_insert_query, insert_tuple)
               connection.commit()
               print("Record inserted successfully into data_sensor table")
               print("Delete file")
               os.remove(location)
except Error as e:
   print("Error while connecting to MySQL", e)
   connection.rollback()
   print("Failed to read insert into MySQL table {}".format(e))
finally:
  # closing database connection
   if(connection.is_connected()):
       cursor.close()
       connection.close()
       print("MySQL connection is closed")
cs


#11. Upload data from text file into NAS database using mysql-python & pandas 에서 몇 라인이 추가되었다.

       # reset primary Auto Increment to 1
       A_I_reset_query = """ALTER TABLE data_sensor AUTO_INCREMENT=1"""
       cursor.execute(A_I_reset_query)

먼저 위 코드는 Primary auto increment를 1로 reset해주는 code이다.
이게 무슨 의미냐면, 이번 source의 경우 우리는 id를 따로 부여하지 않고 DB에 업로드를 했다. 하지만 #08. Insert File to NAS Database From PC using mysql-python through Internet (external address) 에서 우리는 id를 primary A_I로 지정했기 때문에 값을 따로 정해주지 않아도 순차적으로 값이 증가하게 되는 것이다. 해당 내용에 대해서는 다음 사이트를 참고하면 된다.

[DB] MySQL에서 AI(Auto Increment)값 초기화 하기 - UroA 개발 블로그 

만약 위와 같은 코드를 넣지 않는다면 100번째 id를 갖는 data들을 삭제하고 빈 공간에 data를 생성할 때, 첫 data가 101번째 id를 갖게 될 것이다.

       path_dir = 'C:\Data'
       while (1) :
           # if there is no file in the directory, then do nothing
           file_list = os.listdir(path_dir)
           if len(file_list) > 0:
               file_list.sort()
               location = path_dir+'\\'+file_list[0]
               print(location)

os module을 이용한 폴더 탐색 및 폴더 내의 파일 탐색이다.
file_list는 폴더내의 file들을 list형태로 받아오게 되는데, list의 size가 1개 이상일 때만 동작하도록 하였다.
file_list.sort()를 이용해 순차정리가 가능하다.

os.remove(location)

위 함수를 통해 파일제거가 가능하다.

댓글 없음:

댓글 쓰기