갈루아의 반서재

파이썬을 통해 MySQL에 접속하는 방법에 대해 알아보자. 


Download and Install MySQL Connector Python on Linux

본 가이드의 환경은 우분투 18.04 운영체제로, 먼저 pip 를 사용하여 Connector/Python 을 설치하자.

1
:~$ pip install mysql-connector-python
cs

다른 운영체제에 대한 설치방법은 아래 링크를 참조한다. 



Python MySQL Database Connection

Steps to connect MySQL database in Python using MySQL Connector Python

  1. Oracle’s MySQL Connector Python 모듈을 설치한다.
  2. MySQL 연결하기 위해 “MySQL Connector Python” 의 connect() 메소드를 사용한다.
  3. 데이터베이스 작동하기 위한 커서 객체를 생성하기 위해 connect() 메소드가 반환하는 connection 객체를 사용한다. 
  4. 커서 객체와 MySQL 데이터베이스 연결을 종료한다.
  5. 프로세스진행동안 예외가 발생하면 캐치


Create Database in MySQL

예제에서 사용할 python_DB 데이터베이스를 생성한다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1579
Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)
 
Copyright (c) 20002018, Oracle and/or its affiliates. All rights reserved.
 
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
 
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
 
mysql> Create database python_DB;
Query OK, 1 row affected (0.00 sec)
 
cs

mysqlpython.py 라는 이름으로 MySQL 데이터베이스에 접속하기 위한 스크립트를 작성해보자. 

1
~$ nano mysqlpython.py
cs

전체 코드는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
import mysql.connector
from mysql.connector import Error
try:
    connection = mysql.connector.connect(host='localhost',
                             database='python_DB',
                             user='root',
                             password='****************')
    if connection.is_connected():
       db_Info = connection.get_server_info()
       print("Connected to MySQL database... MySQL Server version on ",db_Info)
       cursor = connection.cursor()
       cursor.execute("select database();")
       record = cursor.fetchone()
       print ("Your connected to - ", record)
except Error as e :
    print ("Error while connecting to MySQL", e)
finally:
    #closing database connection.
    if(connection.is_connected()):
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
 
cs

스크립트 실행결과. 정상적으로 접속이 된다.

1
2
3
4
:~$ python mysqlpython.py
Connected to MySQL database... MySQL Server version on  5.7.24-0ubuntu0.18.04.1
Your connected to -  ('python_DB',)
MySQL connection is closed
cs


위 파이썬 MySQL 데이터베이스 연결 예제프로그램의 라인별 해설과 Python MySQL Connection 인수 목록에 대한 설명은 아래 링크를 참조한다. 

https://pynative.com/python-mysql-database-connection/