728x90
    
    
  파이썬을 통해 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
- Oracle’s MySQL Connector Python 모듈을 설치한다.
- MySQL 연결하기 위해 “MySQL Connector Python” 의 connect() 메소드를 사용한다.
- 데이터베이스 작동하기 위한 커서 객체를 생성하기 위해 connect() 메소드가 반환하는 connection 객체를 사용한다.
- 커서 객체와 MySQL 데이터베이스 연결을 종료한다.
- 프로세스진행동안 예외가 발생하면 캐치
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) 2000, 2018, 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 인수 목록에 대한 설명은 아래 링크를 참조한다.
728x90
    
    
  'Season 1 아카이브 > 프로그래밍' 카테고리의 다른 글
| 장고 워드프레스 통합하기 Integrating Django with a wordpress database (0) | 2018.11.15 | 
|---|---|
| 워드프레스 이미지 업로드 사이즈 수정하기 (Nginx) (0) | 2018.11.11 | 
| 우분투 18.04 에 Nginx phpMyAdmin 설치하기 Installing phpMyAdmin for Nginx on Ubuntu 18.04 (0) | 2018.11.09 | 
| MYSQL 시작, 종료, 재시작, 상태보기 How to restart MySQL (0) | 2018.11.08 | 
| MySQL 5.7.24 비밀번호 변경 (0) | 2018.11.08 |