1. mysqlclient
- 파이썬에서는 MySQL. 서버와 통신할 수 있는 파이썬을 데이터베이스 커넥터를 다양하게 지원
- PyMySQL, mysqlclient를 가장 많이 사용함
- 사용법은 비슷하나 속도가 빠른 mysqlclient를 권장하고 있음
파이썬과 연결하려면 데이터에서 드라이버를 만들어 소통할 수 있게 해줘야함
그 드라이버가 바로 ' mysqlclient' 이다.
파이썬과 my sql은 다른 언어이기 때문에 매개체가 필요하다.
![]() ![]() |
1. 접속하기
- My SQLdb.connect(host='IP주소',user='사용자',password='비밀번호',db='DB명')
![]() |
2. cursor 생성하기
- 하나의 DataBase Connection에 대해 독립적으로 SQL문을 실해알 수 있는 작업환경을 제공하는 객체
- 하나의 connection에 동시에 한개의 cursor만 생성할 수 있으며, cursor를 통해 SQL문을 실행하면 실행결과를 튜플 단위로 반환
![]() ![]() |
< My SQL > ![]() ![]() |
< Pythone> ![]() |
3. SQl문 결과 가져오기
- fetchall(): 한번에 모든 tuple을 가져옴. 검색 결과가 매우 많다면 메모리 오버헤드가 발생할 수 있음
- fetchone(): 한번에 하나의 tuple을 가져옴. 다시 fetchone()메서드를 호출하면 다음 데이터를 가져옴
![]() |
![]() |
![]() |
4. dict 형태로 결과를 반환하기
- cursor(MySQLdb.cursors.DictCursor)
![]() |
![]() |
5. cursor와 Connection 닫아주기
- cur.close()
- db.close()
![]() |
2. 데이터 삽입하기
- cursor와 Connection 다시 연결
![]() |
- 데이터 삽입하기
![]() |
![]() ㄴ My SQL에 망고가 들어가 있지 않음 |
![]() |
![]() ㄴ 들어간 것을 확인할 수 있습니다 ㄴ transation 구간에서 저장되었다가 완료되는 반영되고 문제가 생기면 반환되는 성질이 있기 때문에 commit을 실행해야 합니다. |
- 여러 데이터 동시에 삽입하기
![]() |
![]() |
문제
- 회원가입 프로그램을 만들어보자
- 단, 중복 데이터 또는 잘못된 데이터로 인한 오류시 "다시 입력하세요"라는 메세지와 함께 다시 등록
- 단, 회원 가입 후 "추가로 가입하시겠습니까?(Y/N)"을 입력받아 추가로 입력할 수 있도록
import MySQLdb
db = MySQLdb.connect('localhost', 'root', '1234', 'kdt')
cur = db.cursor()
while True:
try:
userid = input('아이디를 입력하세요: ')
userpw = input('비밀번호를 입력하세요: ')
name = input('이름을 입력하세요: ')
hp = input('번화번호를 입력하세요: ')
email = input('이메일을 입력하세요: ')
gender = input('성별을 입력하세요: ')
ssn1 = input('주민번호 앞자리를 입력하세요: ')
ssn2 = input('주민번호 뒷자리를 입력하세요: ')
zipcode = input('우편번호를 입력하세요: ')
address1 = input('주소를 입력하세요: ')
address2 = input('상세주소를 입력하세요: ')
address3 = input('참고사항 입력하세요: ')
sql = 'insert into member (userid, userpw, name, hp, email, gender, ssn1, ssn2, zipcode, address1, address2, address3) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
data = (userid, userpw, name, hp, email, gender, ssn1, ssn2, zipcode, address1, address2, address3)
cur.execute(sql, data)
db.commit()
print('가입되었습니다')
yn = input('추가로 가입하시겠습니까?(Y/N): ')
if yn.lower() == 'n':
print('프로그램을 종료합니다')
break
except Exception as e:
print('다시 입력하세요')
cur.close()
db.close()
![]() |
![]() |
3. 데이터 수정하기
db = MySQLdb.connect('localhost', 'root', '1234', 'kdt')
cur = db.cursor()
sql = 'update member set zipcode=%s, address1=%s, address2=%s, address3=%s where userid=%s'
data = ('12345', '서울', '서초구', '양재동', 'banana')
result = cur.execute(sql, data)
db.commit()
if result > 0:
print('수정되었습니다')
else:
print('에러!')
cur.close()
db.close()

4. 데이터 삭제하기
db = MySQLdb.connect('localhost', 'root', '1234', 'kdt')
cur = db.cursor()
sql = 'delete from member where userid=%s'
result = cur.execute(sql, ('kiwi',))
db.commit()
if result > 0:
print('탈퇴되었습니다')
else:
print('오류!')
cur.close()
db.close()

문제
- 로그인 프로그램을 작성해보자
- 아이디, 비밀번호가 맞을 경우 "로그인 되었습니다", 틀린 경우 "아이디 또는 비밀번호를 확인하세요"라고 출력
db = MySQLdb.connect('localhost', 'root', '1234', 'kdt')
cur = db.cursor()
userid = input('아이디를 입력하세요: ')
userpw = input('비밀번호를 입력하세요: ')
sql = 'select userid from member where userid=%s and userpw=%s'
data = (userid, userpw)
result = cur.execute(sql, data)
if result > 0:
print('로그인되었습니다')
else:
print('아이디 또는 비밀번호를 확인하세요')
cur.close()
db.close()
![]() ![]() |
![]() ![]() |
'DataBase' 카테고리의 다른 글
⏺과제 _ 축구선수관리 프로그램 기획 (0) | 2024.04.01 |
---|---|
4-2. DB를 활용한 단어장 만들기 (0) | 2024.03.28 |
3-3. My SQL 사용자 수정 (0) | 2024.03.27 |
3-2. 뷰(view), 다이어그램(Diagram) (0) | 2024.03.27 |
3-1. MySQL 문자열 함수, 유니온, 서브쿼리 (0) | 2024.03.27 |