null
vuild_
Nodes
Flows
Hubs
Login
MENU
GO
Notifications
Login
⌂
Python으로 MySQL 다루기
Structure
connect
•
pymysql 연결 패턴 정리
db-table
•
DB 만들고 지우는 법
•
테이블 생성과 데이터 타입 선택
write
•
INSERT 단일 행 추가
•
다중 행은 executemany로
read
•
SELECT로 전체 조회하기
•
WHERE로 조건 조회
•
ORDER BY, LIMIT로 정렬과 페이징
advanced
•
UPDATE와 DELETE 패턴
•
NaN → None 변환과 에러 처리
Flow Structure
다중 행은 executemany로
6 / 10
WHERE로 조건 조회
☆ Star
↗ Full
SELECT로 전체 조회하기
#python
#mysql
#pymysql
#select
#fetchall
@devpc
|
2026-05-04 12:41:22
|
GET /api/v1/flows/26/nodes/505?fv=1&nv=1
Context:
Flow v1
→
Node v1
0
Views
1
Calls
# SELECT로 전체 조회하기 ## 전체 조회 패턴 ```python import pymysql conn = pymysql.connect( host='localhost', user='root', password='', db='mydb', charset='utf8' ) try: with conn.cursor() as cursor: cursor.execute('SELECT * FROM sensor_log') result = cursor.fetchall() conn.commit() finally: conn.close() for row in result: print(row) ``` `result`는 **tuple의 tuple**로 반환된다. ``` (1, datetime.datetime(2024,1,1,9,0,0), 'sensor_a', 22.1) (2, datetime.datetime(2024,1,1,9,0,0), 'sensor_b', 35.7) ... ``` --- ## fetch 함수 세 가지 | 함수 | 동작 | 반환 타입 | |------|------|-----------| | `fetchall()` | 쿼리 결과 전체 반환 | `tuple of tuple` | | `fetchone()` | 결과 중 첫 행만 반환 | `tuple` 또는 `None` | | `fetchmany(n)` | 결과 중 n행만 반환 | `tuple of tuple` | ```python # fetchone: 한 행만 필요할 때 cursor.execute('SELECT COUNT(*) FROM sensor_log') count = cursor.fetchone()[0] # fetchmany: 페이지 단위로 처리할 때 cursor.execute('SELECT * FROM sensor_log') while True: rows = cursor.fetchmany(100) if not rows: break process(rows) ``` --- ## 컬럼 이름과 함께 받기 기본 cursor는 tuple을 반환한다. `DictCursor`를 쓰면 dict로 받을 수 있다. ```python conn = pymysql.connect( host='localhost', user='root', password='', db='mydb', charset='utf8' ) try: with conn.cursor(pymysql.cursors.DictCursor) as cursor: cursor.execute('SELECT * FROM sensor_log LIMIT 5') rows = cursor.fetchall() finally: conn.close() for row in rows: print(row['sensor'], row['value']) ``` `DictCursor`를 쓰면 인덱스 대신 컬럼명으로 값에 접근할 수 있어 코드가 읽기 쉬워진다. --- ## 결과를 DataFrame으로 pandas를 쓰는 환경에서는 바로 DataFrame으로 변환할 수 있다. ```python import pandas as pd try: with conn.cursor() as cursor: cursor.execute('SELECT * FROM sensor_log') rows = cursor.fetchall() cols = [d[0] for d in cursor.description] # 컬럼명 finally: conn.close() df = pd.DataFrame(rows, columns=cols) print(df.head()) ``` `cursor.description`은 `[(컬럼명, 타입, ...), ...]` 형태다.
다중 행은 executemany로
WHERE로 조건 조회
// COMMENTS
Newest First
ON THIS PAGE
No content selected.