파이썬 sqlite row_factory로 fetchall() 리스트로 받기

728x90

id = 1,2,3 일 때, 

기존 사용하던대로 사용하면

import sqlite3

conn = sqlite3.connect('my.db')
cur = conn.cursor()
ids = cur.execute('SELECT id FROM users').fetchall()

[(1,), (2,), (3,)] 으로 리스트로 감싸진 튜플들이 나온다.

import sqlite3

conn = sqlite3.connect('my.db')
conn.row_factory = lambda cursor, row: row[0]
c = conn.cursor()
ids = c.execute('SELECT id FROM users').fetchall()

row_factory를 사용하면 

[1, 2, 3] 으로 나온다.

 

row_factory 란

Cursor객체와 원시 행의 결과를 2개의 인수로 받아들이고 tupleSQLite 행을 나타내는 사용자 정의 객체를 반환하는 콜러블입니다.

https://docs.python.org/3/library/sqlite3.html

 

sqlite3 — DB-API 2.0 interface for SQLite databases — Python 3.10.7 documentation

How to use the connection context manager A Connection object can be used as a context manager that automatically commits or rolls back open transactions when leaving the body of the context manager. If the body of the with statement finishes without excep

docs.python.org

 

반응형