-
05 - 2 PYMYSQL (UPDATE, DELETE, SELECT)코린이 유치원/SQL반 2022. 6. 8. 00:24
대소문자 NO 구별의 폐해 만물python을 경험할 수 있는
pymysql의 마지막 정리시간
pymysql 이제 안녕 👋👋
01 Update
update 와 delete 모두 코드 절차는 동일! SQL 구문만 바꾸면 되니깐 긴장 ㄴㄴ
기존 정보에서 키를 모두 + 10cm 해주는 기적의 update 구문을 작성해보자
update_sql = "update test_user set tall = tall + 10" with pymysql.connect(host = '127.0.0.1', port = 3306, user = 'scott', password = 'tiger', db = 'testdb', charset = 'utf8') as connection: with connection.cursor as cursor: cnt = cursor.execute(update_sql) connection.commit()
- SQL 구문 작성법 이외에 connect 하고 cursor 생성하는 방식은 모두 동일
- SQL 구문 작성시 set을 넣어서 값을 update
함수구문
def update_user_by_id(id, name, email, tall, birthday): # 5개의 변수 받아서 update 하는 구문 update_Sql = "update test_user set name = %s, email = %s, tall = %s, birthday = %s where id = %s" with pymysql.connect(host = '127.0.0.1', port = 3306, user = 'scott', password = 'tiger', db = 'testdb', charset = 'utf8') as connection: with connection.cursor as cursor: cnt = cursor.execute(update_sql) connection.commit()
- 5개의 변수를 받고, id는 primary key로 where 구문에서 update 할 값을 찾는 용도로 사용
02 Delete
delete_sql = "delete from test_user where id = %s" with pymysql.connect(host = '127.0.0.1', port = 3306, user = 'scott', password = 'tiger', db = 'testdb', charset = 'utf8') as connection: with connection.cursor as cursor: cnt = cursor.execute(delete_sql, (id, )) # id값 튜플로 지정 connection.commit()
- SQL 구문에서 placeholder로 준 id 값은 execute 문에서 튜플로 주면 된다.
함수구문
def delete_user_by_id(id): delete_sql = "delete from test_user where id = %s" with pymysql.connect(host='127.0.0.1', port=3306, user='scott', password='tiger', db='testdb', charset='utf8') as connection: with connection.cursor() as cursor: cnt = cursor.execute(delete_sql, (id,)) connection.commit() return cnt
- 함수 구문에서 id를 변수로 받고 execute 문에서 id를 튜플로 받는다는 것만 기억!
03 Select
select는 DQL이다. DQL은 Data Query Language의 줄임말
pymysql에서 결과를 조회할 수 있는 방법은 4가지가 있는데, 어떤 방법이 있는지 아래에서 배워보자Go!
01 fetchall()
fetchall은 이름 처럼 모든 행을 반환하는 함수이다.
sql = 'select * from test_user' # select 구문은 단순하게 모든 열을 받는 *로 작성 with pymysql.connect(host='127.0.0.1', port=3306, user='scott', password='tiger', db='testdb', charset='utf8') as connection: with connection.cursor() as cursor: cursor.execute(sql) result = cursor.fetchall() result # 모든 결과 조회
- cursor 뒤에 fetchall을 붙여주면 모든 결과가 조회된다.
02 fetchone()
이름 처럼 조회결과 중 첫번째 행만 반환!
주로 primary key로 등의 조건으로 조회하는데 사용한다
sql = 'select * from test_user where id = %s' with pymysql.connect(host='127.0.0.1', port=3306, user='scott', password='tiger', db='testdb', charset='utf8') as connection: with connection.cursor() as cursor: cursor.execute(sql, (id, )) result = cursor.fetchone() result # 조회 결과가 없으면 None, 있으면 1개의 데이터 반환
- 결과가 한개만 반환 되기 때문에, primary key 같은 조건을 걸어서 해당 조건의 행이 있는지 없는지 체크 용도
03 fetchmany()
many 이름 처럼, 지정한 개수만큼 반환
sql = 'select * from test_user' with pymysql.connect(host='127.0.0.1', port=3306, user='scott', password='tiger', db='testdb', charset='utf8') as connection: with connection.cursor() as cursor: cursor.execute(sql) result = cursor.fetchmany(size = 사이즈지정) result # 사이즈 지정한 개수만큼 결과 출력
04 cursor()
cursor가 iterable 타입인 것을 이용해서 for 문에서 select 실행한 cursor를 사용하면 조회 결과 한행씩 모두 조회할 수 있다.
sql = "select * from test_use" with pymysql.connect(host='127.0.0.1', port=3306, user='scott', password='tiger', db='testdb', charset='utf8') as connection: with connection.cursor() as cursor: cursor.execute(sql) for data in cursor: print(data)
Update, Delete 그리고 Select 까지 4가지 방법을 모두 배워본 pymysql 마지막 시간!
pymysql ㅃㅇ!
'코린이 유치원 > SQL반' 카테고리의 다른 글
05 - 3 PYMYSQL (pd.read_sql) (0) 2022.06.14 05 - 1 PYMYSQL (데이터베이스 연결, 커저 생성, INSERT) (0) 2022.06.07 04 - 2 DDL (CREATE) (0) 2022.06.03 04 - 1 DDL (데이터 타입, 제약 조건) (0) 2022.06.02 03 - 3 JOIN (Self Join, Outer Join) (0) 2022.06.02