Database/MySQL
MySQL 연결 Python 코드 샘플
간디와같은마음
2022. 5. 13. 16:25
아래와 같이 MySQL에 연결하여 테이블 "departments" 데이터를 조회하는 Python 샘플 코드입니다.
데이터를 가져오는 부분을 함수 형태로 썼습니다.
import pymysql
dbhost = '132.145.201.247'
dbuser = 'root'
dbpassword = 'Welcome123!@'
dbname = 'employees'
connection = pymysql.connect(host=dbhost, user=dbuser, password=dbpassword, db=dbname)
def list_data():
try:
cursor = connection.cursor()
sql = "select * from departments"
cursor.execute(sql)
except Exception as ex:
print("ERROR: Cannot fetch data", ex, flush=True)
raise
rows = cursor.fetchall()
for row in rows:
print("{0} {1}".format(row[0], row[1]))
result = list_data()
PyCharm에서 실행한 결과입니다.
<END>