Python에서 mysql을 연동하기 위하여 사용 가능한 라이브러리는 다양합니다. 그 중에서 pymysql라는 라이브러리를 정리해 보겠습니다. ㅇ 참고 사이트
- https://github.com/PyMySQL/PyMySQL
- https://pymysql.readthedocs.io/en/latest/user/installation.html
$ python3 -m pip install PyMySQL
Pymysql 분석
참고 사이트 중 documentation(https://pymysql.readthedocs.io/en/latest/user/installation.html)을 보면 예제가 잘 나와 있습니다. 예제 코드는 아래와 같습니다.
import pymysql.cursors # Connect to the database connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('webmaster@python.org', 'very-secret')) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('webmaster@python.org',)) result = cursor.fetchone() print(result) finally: connection.close()ㅇ pymysql.connect() Python에서 데이터베이스에 접속하기 위해서는 DB접속 정보를 입력하여 연결을 맺은 후, Cursor를 생성하여 우리가 수행하고자 하는 쿼리 만들어 수행하면 됩니다.
- host=‘localhost’ : 데이터베이스 주소
- user=‘user’ : 데이터베이스 계정
- password=‘passwd’ : 데이터베이스 패스워드
- db=‘db’ : 데이터베이스명
- charset=‘utf8mb4’ : 문자 인코딩 방식
- cursorclass=pymysql.cursors.DictCursor : Dictionary 커서를 사용
“[Python] 파이썬에서 mysql 데이터베이스 연결을 위한 pymysql 라이브러리”에 대한 1개의 생각