Programming/Python
[Python] MariaDB 접속 및 버전 확인(PyMySQL)
EstenPark
2016. 4. 17. 14:59
이번에는 Python에서 Mysql 또는 MariaDB 접속해서 정보를 가져오는 방법을 해보도록 하겠습니다. Python에서는 PyMySQL 모듈과 MySQLDB 모둘 두 가지 형태로 접속 할 수 있으며, 이번에는 PyMySQL 모듈을 이용해서 접속 해보도록 하겠습니다.
[root@localhost ~]# su - python [python@localhost source]$ pip3.5 install PyMySQL Collecting PyMySQL Downloading PyMySQL-0.7.2-py2.py3-none-any.whl (76kB) 100% |????????????????????????????????| 77kB 3.1MB/s Installing collected packages: PyMySQL Successfully installed PyMySQL-0.7.2 You are using pip version 7.1.2, however version 8.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command.
2. PyMySQL 모듈을 이용한 MySQL(MariaDB) 접속 후 버전 정보 얻어오는 소스
[python@localhost ~]$ cd source/ [python@localhost source]$ vi mariadb_conn_version.py
import urllib import pymysql from urllib.request import urlopen from bs4 import BeautifulSoup # Open database connection db = pymysql.connect(host='localhost', port=3306, user='root', passwd='maria', db='estdb',charset='utf8',autocommit=True) # prepare a cursor object using cursor() method cursor = db.cursor() # execute SQL query using execute() method. cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method. data = cursor.fetchone() print ("Database version : %s " % data) # disconnect from server db.close()
3. Python 실행
[python@localhost source]$ python mariadb_conn_version.py Database version : 10.1.13-MariaDB
위와 같이 간단한 소스로 MariaDB 서버에 연결 할 수 있습니다.