PyMySQL
PyMySQL
MySQL을 Python에서 사용하면서 데이터를 저장 및 관리를 하면 DB를 다룹니다.
- 블로그 링크에 사진과 함께 MySQL 설치 방법과 WorkBench 사용하는 방법이 나와있다.
연결
import pymysql
# MySQL 서버에 연결합니다.
conn = pymysql.connect(
host = '127.0.0.1', # 호스트 이름
port = 3306,
user = 'root', # 사용자 이름
password = 'alclssha12', # 비밀번호
db = 'sample', # 데이터베이스 이름
charset = 'utf8', # 인코딩 설정
cursorclass=pymysql.cursors.DictCursor # 결과를 딕셔너리 형태로 받아옵니다.
)
테이블 생성
- 전체를 try로 감싸고 진행하는 것이 안전합니다.
try:
--- 아래 코드 ---
finally:
# 연결 종료
conn.close()
# 테이블 생성 쿼리 실행
with conn.cursor() as cursor:
# 쿼리 작성
sql = """
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
"""
# 쿼리 실행
cursor.execute(sql)
데이터 추가
# 데이터 추가 쿼리 실행
with conn.cursor() as cursor:
# 쿼리 작성
sql = "INSERT INTO `users` (`name`, `email`, `age`) VALUES (%s, %s, %s)"
# 데이터 추가
cursor.execute(sql, ('John Doe', 'john@example.com', 25))
cursor.execute(sql, ('Jane Doe', 'jane@example.com', 30))
cursor.execute(sql, ('Bob Smith', 'bob@example.com', 40))
# 변경사항 커밋
conn.commit()
데이터 조회
# 데이터 조회 쿼리 실행
with conn.cursor() as cursor:
# 쿼리 작성
sql = "SELECT * FROM `users`"
# 쿼리 실행
cursor.execute(sql)
# 결과 출력
results = cursor.fetchall()
for result in results:
print(result)
{'id': 22, 'name': 'John Doe', 'email': 'john@example.com', 'age': 25}
{'id': 23, 'name': 'Jane Doe', 'email': 'jane@example.com', 'age': 30}
{'id': 24, 'name': 'Bob Smith', 'email': 'bob@example.com', 'age': 40}
{'id': 25, 'name': 'John Doe', 'email': 'john@example.com', 'age': 25}
{'id': 26, 'name': 'Jane Doe', 'email': 'jane@example.com', 'age': 30}
{'id': 27, 'name': 'Bob Smith', 'email': 'bob@example.com', 'age': 40}
데이터 수정
# 데이터 수정
with conn.cursor() as cursor:
# 특정 데이터 수정
sql = "UPDATE `users` SET name=%s WHERE id=%s"
cursor.execute(sql, ("John", 1))
conn.commit()
데이터 조회
# 데이터 조회
with conn.cursor() as cursor:
# 모든 데이터 조회
sql = "SELECT * FROM `users`"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
{'id': 22, 'name': 'John Doe', 'email': 'john@example.com', 'age': 25}
{'id': 23, 'name': 'Jane Doe', 'email': 'jane@example.com', 'age': 30}
{'id': 24, 'name': 'Bob Smith', 'email': 'bob@example.com', 'age': 40}
{'id': 25, 'name': 'John Doe', 'email': 'john@example.com', 'age': 25}
{'id': 26, 'name': 'Jane Doe', 'email': 'jane@example.com', 'age': 30}
{'id': 27, 'name': 'Bob Smith', 'email': 'bob@example.com', 'age': 40}
데이터 삭제
# 데이터 삭제
with conn.cursor() as cursor:
# 특정 데이터 삭제
sql = "DELETE FROM `users` WHERE id=%s"
cursor.execute(sql, (1,))
conn.commit()
연결 닫기
# 연결 닫기
conn.close()
열 데이터 제약 조건
- PK (Primary Key): 테이블에서 유일한 레코드를 식별하기 위한 기본 키(primary key)를 지정합니다.
- NN (Not Null): 해당 칼럼이 null 값을 가질 수 없도록 제약 조건을 설정합니다.
- UQ (Unique): 해당 칼럼의 값이 유일(unique)해야 함을 지정합니다.
- B (Boolean): 해당 칼럼의 값이 참(true) 또는 거짓(false) 중 하나임을 지정합니다.
- UN (Unsigned): 해당 칼럼의 값이 음수(negative)가 아니어야 함을 지정합니다.
- ZF (Zero Fill): 해당 칼럼의 값이 0으로 채워지도록 설정합니다.
- AI (Auto Increment): 해당 칼럼의 값이 자동으로 증가하도록 설정합니다.
- G (Generated): 해당 칼럼의 값이 데이터베이스에 의해 자동으로 생성되도록 설정합니다.