티스토리 뷰

프로그래밍/Python

[python3] mysql 예제

메모하는습관 2022. 1. 4. 15:38

먼저 PyMySQL을 설치 한다.

$ pip install PyMySQL
Collecting PyMySQL
	Downloading PyMySQL-1.0.2-py3-none-any.whl (43 kB)
		|████████████████████████████████| 43 kB 6.2 MB/s
Installing collected packages: PyMySQL
Successfully installed PyMySQL-1.0.2

 

아래는 PyMySQL을 사용하여 MySQL DB에 데이터를 추가하고 조회하는 예제이다.

import pymysql
  
try:
	conn = pymysql.connect(
		host='127.0.0.1',
		user='user',
		passwd='passwd',
		db='dbname',
		charset='utf8',
		cursorclass=pymysql.cursors.DictCursor)
	cursor = conn.cursor()
    
	# 데이터 추가
	cursor.execute("""
		INSERT INTO users (id, name)
		VALUES (%s, %s)
	""", ('gdhong', '홍길동'))
	conn.commit()
    
	# 데이터 조회
	cursor.execute("""
		SELECT	id, name
		FROM		users
		WHERE		id = %s
	""", ('gdhong'))
	result = cur.fetchall()
	
finally:
	cursor.close()
	conn.close()
  
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday