수업-MySql-파이썬과 데이터베이스-연동하기

JungSik Heo·2025년 1월 4일
0

MySQL

목록 보기
30/33

1.🐍🐬pymysql 라이브러리 설치하기

pip install pymysql

2.🐍🐬파이썬과 MySQL 데이터베이스 연동하기

3.mysql DB 연결

mysql\mysql_example.py

from calendar import c
import pymysql

#utf8: 한글이 문제 없도록 utf8을 사용
conn = pymysql.connect(host='127.0.0.1', user='scott', password='tiger', db='scott', charset='utf8')

#cursor 객체 생성 => 커서 객체의 역활은은 sql 문장을 실행하고 결과를 가져오는 역할
curs = conn.cursor()
sql = "select * from emp"
curs.execute(sql)
rows = curs.fetchall()
print(rows)


#테이블 생성
curs.execute('CREATE TABLE userTable (id char(4), userName char(15), email char(20), birthYear int)')

#데이터 추가
curs.execute("INSERT INTO userTable VALUES( 'hong' , '홍지윤' , 'hong@naver.com' , 1996)")
curs.execute("INSERT INTO userTable VALUES( 'kim' , '김태연' , 'kim@daum.net', 2011)")
curs.execute("INSERT INTO userTable VALUES( 'star' , '별사랑' , 'star@paran.com' , 1990)")
curs.execute("INSERT INTO userTable VALUES( 'yang' , '양지은' , 'yang@gmail.com' , 1993)")


conn.commit() #영구 저장
conn.close() #연결 종료
profile
쿵스보이(얼짱뮤지션)

0개의 댓글