파이썬으로 처음 작업하면서 MySQL을 연결할 일이 생겼다!
찾아보니 pymysql 라이브러리를 사용하면 된다고 해서 사용해보았다 : )
pip install pymysql
pip install python-dotenv
pip install unittest
import unittest
import pymysql
from dotenv import load_dotenv
테스트하려고 unittest
도 import 시켰다.
class TestMysqlConnetion(unittest.TestCase):
load_dotenv()
# test 함수 진입 전에 실행 함수
def setUp(self):
self.con = pymysql.connect(host=os.environ.get('DB_READ'),
user=os.environ.get('DB_USERNAME'),
password=os.environ.get('DB_PASSWORD'),
db=os.environ.get('DB_DATABASE'),
charset='utf8mb4')
self.cur = self.con.cursor(pymysql.cursors.DictCursor)
# select test code
def test_select(self):
sql = "SELECT * FROM TABLE_NAME"
self.cur.execute(sql)
list = self.cur.fetchall()
for item in list:
print(f"{item['id']} ::::: {item['name']}")
self.assertTrue( len(list) > 0 )
os
, dotenv
를 통해 .env 파일에 존재하는 환경파일을 가져와서 DB 연결한다. host
: 디비 호스트user
: 디비 사용자password
: 디비 비밀번호 db
: 데이터베이스 charset
: 디비 charsetpymysql.cursors.DictCursor
옵션을 추가해야만 select 시에 컬럼 이름으로 조회가능item[0]
으로 조회 self.cur = self.con.cursor()
item['id']
로 조회 가능 self.cur = self.con.cursor(pymysql.cursors.DictCursor)