๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
IT-Engineering/Python

ํŒŒ์ด์ฌ Python์œผ๋กœ mysql ์—ฐ๊ฒฐํ•˜๊ธฐ(mysql-connector-python ๊ธฐ๋ณธ ์‚ฌ์šฉ๋ฒ•)

by ๐Ÿงž‍โ™‚๏ธ 2021. 12. 31.
๋ฐ˜์‘ํ˜•

ํŒŒ์ด์ฌ(Python)์œผ๋กœ MySQL ์—ฐ๋™ํ•˜๊ธฐ

 

์ด๋ฒˆ ํฌ์ŠคํŒ…์—์„œ๋Š” ํŒŒ์ด์ฌ(Python)์„ ํ™œ์šฉํ•˜์—ฌ ๋ณธ์ธ PC์— ์„ค์น˜๋œ mysql ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ ‘๊ทผํ•˜์—ฌ ์—ฐ๋™๋œ DB์— ์งˆ์˜๋ฌธ(์ฟผ๋ฆฌ๋ฌธ)์„ ๋‚ ๋ ค์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์ถœ๋ ฅํ•ด๋ณด๋Š” ๊ฒƒ๊นŒ์ง€ ์‚ดํŽด๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

 1. MySQL ์„ค์น˜

๋ณธ ํฌ์ŠคํŒ…์˜ ๋‚ด์šฉ์€ MySQL์ด ์„ค์น˜๋œ ๊ฒƒ์œผ๋กœ ๊ฐ€์ •ํ•ฉ๋‹ˆ๋‹ค(์ด ํฌ์ŠคํŒ…์˜ ๊ฒฝ์šฐ 5.7๋ฒ„์ „ ์‚ฌ์šฉ). ๊ทธ๋Ÿผ์—๋„ ์„ค์น˜ ๋งํฌ๋ฅผ ์ฒจ๋ถ€ํ•˜๋‹ˆ ์ฐธ๊ณ ํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.

mysql 5.7 ์„ค์น˜ ํŒŒ์ผ ๋งํฌ:
 

 

๋‹ค๋ฅธ ๋ฒ„์ „์„ ๊ณ ๋ฅด๊ณ  ์‹ถ์œผ์‹œ๋ฉด:

 

 2. mysql-connector-python ์„ค์น˜

 

ํŒŒ์ด์ฌ(Python)์—์„œ mysql์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” mysql-connector-python์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์„ค์น˜ ๋ช…๋ น์–ด๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

pip install mysql-connector-python

 

 3. Python ์ฝ”๋“œ๋กœ mysql ํŠน์ • ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ฐ๊ฒฐํ•˜๊ธฐ

 

(1) MySQL Connector๋กœ ์—ฐ๊ฒฐํ•˜๊ธฐ : ๊ฐ€์žฅ simpleํ•œ ๋ฒ„์ „

 

user์—๋Š” ์‚ฌ์šฉ์ž id๋ฅผ password์—๋Š” ์‚ฌ์šฉ์ž ์•”ํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. host์—๋Š” mysql์„œ๋ฒ„ ์ฃผ์†Œ๋ฅผ ์ž…๋ ฅํ•ด์•ผ ํ•˜๊ณ , database์—๋Š” ์—ฐ๊ฒฐ์„ ์›ํ•˜๋Š” database๋ช…์„ ์ž…๋ ฅํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

import mysql.connector

# (1) MYSQL ์—ฐ๊ฒฐ
cnx = mysql.connector.connect(user='root', password='password', 
                              host='127.0.0.1',
                              database='db1') 
# (2) MYSQL ์—ฐ๊ฒฐ ์ข…๋ฃŒ
cnx.close()
 

(2) MySQL Connector๋กœ ์—ฐ๊ฒฐํ•˜๊ธฐ : ๋ณด๋‹ค ์•ˆ์ „ํ•œ ์ƒ์„ธ ๋ฒ„์ „

 

์˜ˆ์™ธ ์ฒ˜๋ฆฌ(Try-Exception)์™€ ์งˆ์˜(์ฟผ๋ฆฌQuery)๋ฅผ ๋‚ ๋ฆฌ๊ณ  ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›์•„์˜ค๋Š” ์˜ˆ์ œ๋ฅผ ํฌํ•จํ•œ ๋ฒ„์ „์ž…๋‹ˆ๋‹ค. 

์•„๋ž˜์˜ ์ฝ”๋“œ์ฒ˜๋Ÿผ ์„œ๋ฒ„์˜ mysql ๋ฒ„์ „๋„ ์ฐ์–ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

import mysql.connector

try:
    # (1) MYSQL ์—ฐ๊ฒฐ 
    connection = mysql.connector.connect(
        host = '127.0.0.1',
        database = 'db1',  
        user = 'root',
        password = 'password'   
    )

    if connection.is_connected():
        db_info = connection.get_server_info()
        print('mysql Version : ', db_info)  

        # (2) ์ปค์„œ ๋งŒ๋“ค๊ธฐ 
        cursor = connection.cursor()

        # (3) ์›ํ•˜๋Š” ์ฟผ๋ฆฌ๋ฌธ ๋“ฑ ์‹คํ–‰ 
        cursor.execute('show tables;')
        

        # (4) ์ปค์„œ์—์„œ ์‹คํ–‰ ๊ฒฐ๊ณผ ํ•œ์ค„์”ฉ ๊ฐ€์ ธ์˜ค๊ธฐ         
        row = cursor.fetchone()
        while row is not None:
            print(row)
            row = cursor.fetchone()

except Error as e:
    print('Database Error: ',e) 

finally:
    # (5) ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ปค์„œ์™€ ์ปค๋„ฅ์…˜์„ ๋ชจ๋‘ ๋‹ซ์Œ 
    cursor.close()
    connection.close()
    print('MySQL Connection Close')

 

python์œผ๋กœ mysql ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ํ™œ์šฉํ•˜๋Š”๋ฐ ๋„์›€์ด ๋˜์…จ์œผ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค. ๋„์›€์ด ๋˜์…จ๋‹ค๋ฉด, ์ข‹์•„์š”์™€ ๋Œ“๊ธ€ ๋‚จ๊ฒจ์ฃผ์‹œ๋ฉด ํฌ์ŠคํŒ…์„ ํ•˜๋Š”๋ฐ ํฐ ํž˜์ด ๋ฉ๋‹ˆ๋‹ค. ๐Ÿ˜Š

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€