본문 바로가기

Script

[Python] MySQL 데이터 반복 입력

사전 준비 사항

Python3.8 설치 (pip3)

yum install -y centos-release-scl

yum install -y rh-python38

scl enable rh-python38 bash

echo 'source scl_source enable rh-python38' >> ~/.bashrc

source ~/.bashrc

 

pip3 install mysql-connector-python

 

반복 데이터 입력 스크립트 작성 (작성시 #설명 부분은 삭제)

vi insertdata.py

 

import mysql.connector
from mysql.connector import Error
import logging

 

#작업 로그 기록
logging.basicConfig(filename='db_insert.log', level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

 

#DB연결을 위한 정보 입력
def insert_data(records):
    try:
        connection = mysql.connector.connect(
            host='localhost (DB서버가 별도로 있으면 해당 서버의 IP입력)',
            database='데이터를 넣을 DB명',
            user='계정명',
            password='패스워드'
        )

        if connection.is_connected():
            cursor = connection.cursor()
            sql_insert_query = """INSERT INTO member_table (mb_id, mb_pw, address, mb_tell) VALUES (%s, %s, %s, %s)"""

            cursor.executemany(sql_insert_query, records)
            connection.commit()
            logging.info(f"{cursor.rowcount} records inserted successfully into member_table")

    except mysql.connector.Error as error:
        logging.error(f"Failed to insert record into MySQL table {error}")

    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            logging.info("MySQL connection is closed")

 

#DB에 적재할 데이터 값 설정 (user01/user01/지역/전화번호) 형식으로 user01부터 user100000 까지 생성
if __name__ == "__main__":
    data = [(f'user{i:05}', f'user{i:05}', 'seoul', f'010-1234-{i:04}') for i in range(1, 100001)]
    logging.info("Starting data insertion")
    insert_data(data)
    logging.info("Data insertion completed")

 

내용 저장 후 python3 insertdata.py 로 실행

 

위 스크립트를 실행하게 되면 아래와 같이 DB의 member_table 이라는 테이블에 데이터가 적재된다.

 

.

.

.

 

해당 스크립트의 작업 기록은 스크립트 첫부분 logging 부분에 지정한 파일명으로 아래와 같이 실행위치에 기록된다.