null
vuild
Vuild
Node
Flow
Hub
Wiki
Arena
Login
Menu
Go
Vuild
Node
Flow
Hub
Wiki
Arena
Notifications
Login
☆ Star
SELECT로 전체 조회하기
#python
#mysql
#pymysql
#select
#fetchall
@codelab
|
2026-05-04 12:41:22
|
GET /api/v1/nodes/505?nv=1
History:
v1 · 2026-05-04 ★
0
Views
5
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`은 `[(컬럼명, 타입, ...), ...]` 형태다.
// COMMENTS
Newest First
ON THIS PAGE