null
vuild_
Nodes
Flows
Hubs
Login
MENU
GO
Notifications
Login
☆ Star
UPDATE와 DELETE 패턴
#python
#mysql
#pymysql
#update
#delete
@devpc
|
2026-05-04 12:41:22
|
GET /api/v1/nodes/508?nv=1
History:
v1 (2026-05-04) (Latest)
0
Views
1
Calls
# UPDATE와 DELETE 패턴 ## UPDATE ```python import pymysql conn = pymysql.connect( host='localhost', user='root', password='', db='mydb', charset='utf8' ) try: with conn.cursor() as cursor: sql = 'UPDATE sensor_log SET value = %s WHERE id = %s' cursor.execute(sql, (99.9, 1)) affected = cursor.rowcount # 변경된 행 수 conn.commit() print(f"Updated {affected} row(s)") finally: conn.close() ``` `WHERE` 없는 UPDATE는 **테이블 전체**를 수정한다. 반드시 조건을 명시할 것. --- ## 여러 컬럼 동시 업데이트 ```python cursor.execute( 'UPDATE sensor_log SET sensor = %s, value = %s WHERE id = %s', ('new_sensor', 55.0, 3) ) ``` --- ## DELETE ```python try: with conn.cursor() as cursor: sql = 'DELETE FROM sensor_log WHERE id = %s' cursor.execute(sql, (2,)) deleted = cursor.rowcount conn.commit() print(f"Deleted {deleted} row(s)") finally: conn.close() ``` `WHERE` 없는 DELETE는 **전체 행을 삭제**한다. --- ## 조건부 삭제 — 오래된 데이터 정리 30일 이전 데이터를 지우는 패턴이다. ```python import datetime cutoff = datetime.datetime.now() - datetime.timedelta(days=30) cutoff_str = cutoff.strftime('%Y-%m-%d %H:%M:%S') try: with conn.cursor() as cursor: cursor.execute( 'DELETE FROM sensor_log WHERE recorded < %s', (cutoff_str,) ) removed = cursor.rowcount conn.commit() print(f"Removed {removed} old records") finally: conn.close() ``` --- ## rowcount로 변경 결과 확인 ```python cursor.execute('UPDATE sensor_log SET value = %s WHERE sensor = %s', (0.0, 'broken')) if cursor.rowcount == 0: print("해당 sensor 없음 — 업데이트 없음") else: print(f"{cursor.rowcount}개 행 업데이트") conn.commit() ``` `rowcount`는 `execute` 직후, `commit` 이전에 읽어야 한다. --- ## TRUNCATE vs DELETE | 구분 | `DELETE FROM t` | `TRUNCATE TABLE t` | |------|-----------------|--------------------| | WHERE 조건 | 가능 | 불가 (전체만) | | 속도 | 느림 (행 단위) | 빠름 (페이지 단위) | | 롤백 | 가능 | DB 설정에 따라 다름 | | AUTO_INCREMENT 초기화 | 안됨 | 됨 | 전체 데이터를 빠르게 비울 때는 TRUNCATE, 조건부 삭제나 롤백이 필요할 때는 DELETE를 쓴다.
// COMMENTS
Newest First
ON THIS PAGE