728x90
Python에서 Mysql(MariaDB) 접속해서 Table 조회해서 JSON 변환하자.
먼저 pymysql를 설치하자.
pip install pymysql
※ 소스
# -*- coding: utf-8 -*-
import json
import pymysql
con = pymysql.connect(host='localhost', user='', password='',
db='', charset='utf8', # 한글처리 (charset = 'utf8')
autocommit=True, # 결과 DB 반영 (Insert or update)
cursorclass=pymysql.cursors.DictCursor # DB조회시 컬럼명을 동시에 보여줌
)
cur = con.cursor()
sql = "select * from tab"
cur.execute(sql)
rows = cur.fetchall()
con.close() # DB 연결 종료
print(rows)
print(json.dumps(rows, default=str, ensure_ascii=False))
#FILE_NAME = "./db/json_data.json"
#f = open(FILE_NAME, 'w', encoding='utf-8')
#f.write(json.dumps(rows, default=str, ensure_ascii=False))
#f.close()
728x90
반응형
'Software > Python' 카테고리의 다른 글
Python 시작하기 - JSON 변환 (0) | 2024.06.23 |
---|---|
Python 시작하기 - CSV 저장 (0) | 2024.06.23 |
Python 시작하기 - CSV읽기 및 JSON변환 (0) | 2024.06.23 |
Python 시작하기 - BeautifulSoup (0) | 2024.06.22 |
Python 시작하기 -Web Page 읽기 (0) | 2024.06.22 |