☆IT 개발 프로그램☆/Phthon

[파이썬/Python] mysql connector 라이브러리로 MySql 연동하기

호기심을 품고사는 중 2020. 6. 4. 15:03

전제 조건

외장 라이브러리의 사전 설치를 요한다. 맥/리눅스 사용자는 콘솔에서 아래의 명령어로 바로 설치하는 것을 권장한다.

# MySql 8.0 이상 유저
pip install mysql-connector-python

# 하위 버전
pip install mysql.connector

Pycharm의 경우 프로그램 안에서 라이브러리 설치도 지원한다.

Pycharm - Preference - Project: 프로젝트명 - Project Interpreter 으로 이동, 하단의 + 를 클릭하여 검색, 설치가 가능하다.

 


 

코드 전개

python으로 접근할 mySql table

import mysql.connector

#------------------------------------------------------#

mysql_con = None

#------------------------------------------------------#
def query_executor(cursor, param1, param2):
    sql = "select * from food where name = %s or name = %s ;"
    cursor.execute(sql, (param1, param2))
#------------------------------------------------------#


if __name__ == "__main__":


    try:

        mysql_con = mysql.connector.connect(host='localhost', port='3306', database='test', user='root', password='password')
                                            
        mysql_cursor = mysql_con.cursor(dictionary=True)

        query_executor(mysql_cursor, 'sushi', 'mcdonalds')

        for row in mysql_cursor:
            print('price is: '+str(row['price']))

        mysql_cursor.close()



    except Exception as e:
        print(e.message)


    finally:
        if mysql_con is not None:
            mysql_con.close()
            

 


 

1. 호스트, 포트, 데이터베이스, 유저, 패스워드를 설정하여 mysql에 연결한다. 

mysql_con = mysql.connector.connect(host='localhost', port='3306', database='test', user='root', password='password')

 

2. 쿼리를 실행할 함수를 커서에 올리고, 파라미터와 함께 실행한다. SQL Injection 공격에 대비하기 위하여 쿼리는 반드시 파라미터화 해주어야한다.

 

query_executor(mysql_cursor, 'sushi', 'mcdonalds')

참고로 파라미터를 1개만 사용할 경우는 syntax가 조금 다르므로 주의를 요한다. 파라미터 뒤에 콤마를 입력 하고 괄호를 닫아준다.

def query_executor(cursor, param):
    sql = "select * from food where name = %s ;"
    cursor.execute(sql, (param,))
    

 

3. mysql에서 쿼리를 실행한 output이 커서안에 들어온다. (mysql_cursor) for each문으로 output row들을 받아와서 print문으로 출력한다. 

 

for row in mysql_cursor: 
      print('price is: '+str(row['price']))

실행 결과 스크린샷