hjoon0510 / research-journal

기록일지 (문제, 이슈, 에러, 스크린샷, 작업내용, 해결방법 등을 기록하는 저장소입니다.)
Apache License 2.0
1 stars 0 forks source link

20101003 (python으로 mysql db에 사회적 거리두기 데이타를 저장하기) #107

Open hjoon0510 opened 3 years ago

hjoon0510 commented 3 years ago

이곳은 프로젝트의 작업 내용들을 기록 및 보관하는 곳입니다. 수행한 작업들을 체계적으로 기록하면 문제들을 효과적으로 해결이 가능하고, 반복되는 실수들을 최소화하는데 큰 도움을 제공합니다.

작업내용

파이썬으로 mysql db에 insert명령으로 데이타 저장하기 위한 파이썬 코드를 작성하였다. 구글사이트에서 파이썬을 이용하여 mysql 데이타베이스에 데이타를 저장하는 방법을 찾아서 공부한후에 예제 코드를 작성해보았다.

문제원인

해결방법

#

@author Hyeonjoon Lim

@brief a configuration file to manage variables

#

A configuration file is to simply write a separate file

that contains Python code

@see https://hackernoon.com/4-ways-to-manage-the-configuration-in-python-4623049e841b

mysql = {"host" : "localhost", "user" : "root", "passwd": "raspberry", "db" : "sbdb" }

Create table as per requirement

table1 = {"name": "upload_file", "sql" : """CREATE TABLE upload_file ( file_id VARCHAR(255) NOT NULL PRIMARY KEY, name_orig VARCHAR(255), name_save VARCHAR(255), reg_time TIMESTAMP NOT NULL )""" }

Specify Site and Location for COVID-19 social distancing

covid_sd = {"site" : "매탄공원", "location" : "공연장", "description" : "sbdb" }

* test.py
```bash
# -*- coding: utf-8 -*-
print('정보들을 데이타베이스의 테이블에 삽입합니다.')

# Mysql Database: Insert Into....
# @see 
# https://www.tutorialspoint.com/python/python_database_access.htm
# https://www.w3schools.com/python/python_mysql_insert.asp

import MySQLdb
import config as cfg
from datetime import datetime

timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(timestamp)

# Open database connection
db = MySQLdb.connect(cfg.mysql['host'],cfg.mysql['user'],cfg.mysql['passwd'],cfg.mysql['db'])

# Prepare a cursor object using cursor() method
cursor = db.cursor()

# Prevent broken korean statements
db.query("set character_set_connection=utf8;")
db.query("set character_set_server=utf8;")
db.query("set character_set_client=utf8;")
db.query("set character_set_results=utf8;")
db.query("set character_set_database=utf8;")

# Run a mysql command
violation=6
try:
    sql = """INSERT INTO covid_sd (time, site, location, violation) VALUES (%s, %s, %s, %s) """
    record_tuple = (timestamp, cfg.covid_sd['site'], cfg.covid_sd['location'], violation)
    cursor.execute(sql, record_tuple)
    db.commit()
    cursor.close()
    print("Record inserted successfully into a table.")
except:
    db.rollback()
    print("Failed to insert a record into a table.")

# disconnect from server
db.close()

image

이상.