pymysql은 파이썬을 활용하여 MySQL 에서 데이터베이스를 조작했던 것처럼 사용할 수 있도록 하는 라이브러리다.- PyMySQL Docs
- PyMySQL Github
PyMySQL 라이브러리 설치!pip install pymysql
PyMySQL 라이브러리 임포트import pymysql
PyMySQL 라이브러리 버전 확인pymysql.__version__
pymysql.connect(host=서버IP주소, user=사용자,
password=암호, db=데이터베이스, charset=문자세트)
연결자 = pymysql.connect(연결옵션)
conn = pymysql.connect(host='127.0.0.1',
user='crawluser'
password='********',
db='crawlDB',
charset='utf8')
conn
- 출력
<pymysql.connections.Connection at 0x1f205e05730>
cursor이름 = 연결자.cursor()
cur = conn.cursor()
cur
- 출력
<pymysql.cursors.Cursor at 0x1f205f24ec0>
커서이름.execute() 함수의 매개변수로 넘겨주면 SQL문이 데이터베이스에서 실행cursor이름.execute(SQL문): 한개 행의 데이터 처리cursor이름.executemany(SQL문): 여러 행의 데이터 처리# 테이블 생성 SQL
sql1 = 'DROP TABLE IF EXISTS customer;'
sql2 = '''
CREATE TABLE customer (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(20) NOT NULL,
tel CHAR(13),
birth DATE
);
'''
cur.execute(sql1)
cur.execute(sql2)
- 출력
0
cursor이름.execute(삽입SQL문)sql = '''
INSERT INTO customer (id, name, tel, birth)
VALUES (1, '김바람', '010-123-1111', '2000-01-01'),
(2, '남구름', '010-222-1111', '2010-01-01'),
(3, '서바다', '010-321-2111', '2001-05-01'),
(4, '홍하늘', '010-123-1311', '2010-02-01');
'''
cur.execute(sql)
- 출력
4
연결자.commit()conn.commit()
with 문과 %s 를 활용해서 데이터를 삽입할 수도 있다. 이때는 cur.execute(sql, data) 를 실행한다.# 한 행을 삽입하는 경우
data = (5, '이방', '010-443-1111', '1981-10-10')
with conn.cursor() as cur:
sql = 'INSERT INTO customer (id, name, tel, birth) VALUES (%s, %s, %s, %s);'
cur.execute(sql, data)
conn.commit()
# 여러 행을 삽입하는 경우 (executemany)
data_list = [(6, '성춘향', '010-123-3333', '2010-10-10'),
(7, '이몽룡', '010-444-7777', '2009-05-10')]
with conn.cursor() as cur:
sql = 'INSERT INTO customer (id, name, tel, birth) VALUES (%s, %s, %s, %s);'
cur.executemany(sql, data_list)
conn.commit()
execute 를 for문 으로 반복하여 삽입할 수 있다.# 여러 행을 삽입하는 경우 (for 문)
cur = conn.cursor()
data_list = [(8, '강하늘', '010-777-3333', '2011-10-10'),
(9, '최장군', '010-555-7777', '2019-05-10')]
sql = 'INSERT INTO customer (id, name, tel, birth) VALUES (%s, %s, %s, %s);'
for dt in data_list:
cur.execute(sql, dt)
conn.commit()
연결자.close()conn.close()
commit(), 오류발생시 rollback()# DB연결객체 생성
conn = pymysql.connect(host='127.0.0.1',
user='crawluser',
password='********',
db='crawlDB',
charset='utf8')
# 데이터 준비
data_list = [(10, '성자', '010-123-0099', '2001-03-10'),
(11, '방식', '010-444-7788', '2008-12-10')]
sql = 'INSERT INTO customer (id, name, tel, birth) VALUES (%s, %s, %s, %s);'
# 데이터 삽입
try:
with conn.cursor() as cur:
cur.executemany(sql, data_list)
conn.commit()
print(f'{len(data_list)}행 삽입 완료')
except Exception as e:
conn.rollback()
print(f'{e}: 오류 발생, 롤백 진행')
finally:
conn.close()
- 출력
2행 삽입 완료