Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- append()
- count()
- matplotlib
- del
- 반복문
- 최솟값
- len()
- insert()
- IN
- sklearn
- wcss
- numpy
- Machine Learning
- Dictionary
- function
- dendrogram
- hierarchical_clustering
- string
- 덴드로그램
- DataFrame
- DataAccess
- data
- nan
- Python
- 최댓값
- elbow method
- list
- pandas
- 분류 결과표
- analizer
Archives
- Today
- Total
개발공부
파이썬 환경에서 MySQL 연결하는 법, 예제 본문
MySQL에 만들어져 있는 recipe_db 가 있다.

이 DB에 대한 접속을 Python 코드로 하는 방법은 아래와 같다.
먼저 MySQL에서 recipe_db에만 접속할 수 있는 user를 먼저 만들자.
use mysql;
create user 'recipe_user'@'%' identified by 'recipe1234';
grant all on recipe_db.* to 'recipe_user'@'%';
그 후에 Visual Studio Code에서 recipe_db에 접속하는 방법은 아래와 같다.
아래 라이브러리를 설치한다.
pip install mysql-connector-python
DBMS에 연결하는 함수
import mysql.connector
def get_connection() :
connection = mysql.connector.connect(
host = '#host#',
database = 'recipe_db',
user = 'recipe_user',
password = 'recipe1234',
)
return connection
데이터를 추가하는 법
name = '순두부'
description = '순두부찌개 만드는법'
cook_time = 45
directions = '물 넣고 두부 넣고 조개 넣고 끓인다.'
try :
# 데이터 insert
# 1. DB에 연결
connection = get_connection()
# 2. 쿼리문 만들기
query = '''insert into recipe
(name, description, cook_time, directions)
values
(%s, %s, %s, %s);'''
# recode 는 튜플 형태로 만든다.
recode = (name, description, cook_time, directions)
# 3. 커서를 가져온다.
cursor = connection.cursor()
# 4. 쿼리문을 커서를 이용해서 실행한다.
cursor.execute(query, recode)
# 5. 커넥션을 커밋해줘야 한다 => 디비에 영구적으로 반영하라는 뜻
connection.commit()
# 6. 자원 해제
cursor.close()
connection.close()
except mysql.connector.Error as e :
print(e)
cursor.close()
connection.close()'Python > Basic' 카테고리의 다른 글
| 파이썬으로 압축파일 푸는 방법 (0) | 2022.06.15 |
|---|---|
| [Python] 구글 맵(google maps) API - Geocoding API 설정하는 방법 (0) | 2022.05.04 |
| [Python] relativedelta를 이용해 날짜 연산하기 (0) | 2022.04.27 |
| [Python] parse, 문자열 날짜를 datetime으로 변경 (0) | 2022.04.27 |
| [Python] time 모듈을 이용한 UTC시간, Local 시간 (0) | 2022.04.27 |