-
[pymysql] Database 연동, csv 파일을 DB로 넣고 빼기 & 로그찍기2카테고리 없음 2022. 11. 29. 11:17
미션 : config로 불러온 컬럼명이랑 db 컬럼명이랑 불일치할 때 하는 조치
import logging import pymysql import csv import pandas as pd class MysqlDB(): def __init__(self): self.conn = 0 self.cursor = 0 self.conn = 0 def dbconnect(self): # conn = pymysql.connect(host=connect_info['host'], port=3306, user='root', password='password', db='emp', charset='utf8') self.conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='emp', charset='utf8') return self.conn def csv_to_db(self, config, col_names): openpath = config.readpath if '\\' in openpath: openpath = openpath.replace('\\', '/') file = open(openpath, 'r') csvReader = csv.reader(file) cursor = self.conn.cursor() col_nms = col_names for row in csvReader: name = (row[0]) email = (row[1]) dept = (row[2]) salary = (row[3]) # try : sql = """INSERT INTO employee ("""+ str(col_nms[0]) + ", "+ str(col_nms[1]) +", "+ str(col_nms[2]) + ", " + str(col_nms[3]) + """) VALUES (%s, %s, %s, %s)""" # except : # sql = """INSERT INTO employee (Name, Email, Department, Salary) VALUES (%s, %s, %s, %s)""" cursor.execute(sql, row) # pymysql.err.OperationalError: (1054, "Unknown column 'Sal' in 'field list'") >> 만약 field list에 없다면 replace로 바꿔라 """ if col_nm not in field : df.rename({col_nm} : {rename}) """ def db_to_csv(self, savepath): conn = self.dbconnect() cursor = conn.cursor() sql = """SELECT * from employee""" cursor.execute(sql) df = pd.read_sql_query(sql, conn) df.to_csv(savepath, index=False) def db_commit(self): self.conn.commit() def db_close(self): self.conn.close()반응형