// it's for Latex

pages

[How to connect Python programs to MariaDB in NAS] #11. Upload data from text file into NAS database using mysql-python & pandas

이제 드디어 업로드를 할 시간이다.


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



1. Database에 table 생성하기

해당부분은 이미 #08. Insert File to NAS Database From PC using mysql-python through Internet (external address) 에서 설명한 바 있다.
자신의 환경에 맞도록 (insert될 data의 종류나 개수 등) setting하면 된다.

2. python programming


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
#!/usr/bin/python
import mysql.connector as mariadb
from mysql.connector import Error
import pandas as pd
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)
       df = pd.read_csv('C:\Data\\20190624-14-32-30-646.txt',
                        skiprows=1,
                        skipfooter=1027,
                        sep='\t')
       print(df)
       id = 1
       date_time = df.iloc[0,0]
       print("date_time : ", date_time)
       time_rms = df.iloc[0,5]
       print("time_rms : ", time_rms)
       time_peak = df.iloc[04]
       print("time_peak : ", time_peak)
       time_crest_factor = df.iloc[06]
       print("time_crest_factor : ", time_crest_factor)
       frequency_peak_1 = df.iloc[08]
       print("frequency_peak_1 : ", frequency_peak_1)
       frequency_peak_2 = df.iloc[010]
       print("frequency_peak_2 : ", frequency_peak_2)
       frequency_peak_3 = df.iloc[012]
       print("frequency_peak_3 : ", frequency_peak_3)
       frequency_peak_4 = df.iloc[014]
       print("frequency_peak_4 : ", frequency_peak_4)
       frequency_peak_5 = df.iloc[016]
       print("frequency_peak_5 : ", frequency_peak_5)
       frequency_peak_6 = df.iloc[018]
       print("frequency_peak_6 : ", frequency_peak_6)
       frequency_band_1 = df.iloc[09]
       print("frequency_band_1 : ", frequency_band_1)
       frequency_band_2 = df.iloc[011]
       print("frequency_band_2 : ", frequency_band_2)
       frequency_band_3 = df.iloc[013]
       print("frequency_band_3 : ", frequency_band_3)
       frequency_band_4 = df.iloc[015]
       print("frequency_band_4 : ", frequency_band_4)
       frequency_band_5 = df.iloc[017]
       print("frequency_band_5 : ", frequency_band_5)
       frequency_band_6 = df.iloc[019]
       print("frequency_band_6 : ", frequency_band_6)

       sql_insert_query = """ INSERT INTO `table you've maden`
                                 (`id`, `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,%s)"""

       insert_tuple = (id,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")

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

#10. Parsing text data using Python pandas module 에서 몇 라인이 추가되었다.

살펴보면 다음과 같다.

 sql_insert_query = """ INSERT INTO `table you've maden`
                                 (`id`, `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,%s)"""

먼저 query 형태를 만든다. table에 다음과 같은 data들을 insert한다는 의미이다.

insert_tuple = (id,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)

필자의 경우엔 insert할 data가 많기 때문에 tuple 형태로 사용하게 된다.
해당 예제는 다음 사이트에서 참고할 수 있다.

Using Python variables in a MySQL INSERT query 

result = cursor.execute(sql_insert_query, insert_tuple)

위에서 만든 query를 inser_tuple 값을 대입하여 execute 시키면 최종적으로 우리가 수행해야 할 결과가 생성된다.

connection.commit()
       print("Record inserted successfully into data_sensor table")

이후 commit()을 해주면 실제로 Database에 upload를 할 수 있게된다.











댓글 없음:

댓글 쓰기