Mapping result rows to namedtuple in python sqlite -
i playing bit python api sqlite3, have little table store languages id, name , creation_date fields. trying map raw query results namedtuple
docs recommend, way can manage rows in more readable way, here namedtuple
.
languagerecord = namedtuple('languagerecord', 'id, name, creation_date')
the code docs suggest mapping follows:
for language in map(languagerecord._make, c.fetchall()): # languages
this fine when want return collection of languages in case want retrieve 1 language:
c.execute('select * language name=?', (name,))
so first attempt this:
language = map(languagerecord._make, c.fetchone())
this code doesn't works because fetchone()
returns tuple instead list 1 tuple, map
function tries create 3 namedtuples
1 each tuple field thought.
my first approach solve explicitly create list , append tuple result, like:
languages = [] languages.append(c.fetchone()) language in map(languagerecord._make, languages): # language
my second approach use fetchall()
although want 1 record. can set name field unique
constrain in database in order garantize 1 result.
for language in map(languagerecord._make, c.fetchall()): # languages
another approach use fetchall()[0]
without unique
constrain garantize 1 result.
my question best , common way deal problem, should use fetchall
maintain common interface , let database manage uniqueness logic? or should create list explicitly in approach 1? there more easy way accomplish task?
there easier way! sqlite3 provides way user define "row factories". these row factories take cursor , tuple row , can return whatever type of object wants.
once set row factory with
con.row_factory = my_row_factory
then rows returned cursor result of my_row_factory
applied tuple-row. example,
import sqlite3 import collections languagerecord = collections.namedtuple('languagerecord', 'id name creation_date') def namedtuple_factory(cursor, row): return languagerecord(*row) con = sqlite3.connect(":memory:") con.row_factory = namedtuple_factory cur = con.cursor() cur.execute("select 1,2,3") print(cur.fetchone())
yields
languagerecord(id=1, name=2, creation_date=3)
for example of how define namedtuple factory, see this post.
by way, if set
conn.row_factory = sqlite3.row
then rows returned dicts, keys table's column names. thus, instead of accessing parts of namedtuple things row.creation_date
use builtin sqlite3.row
row factory , access equivalent row['creation_date']
.
Comments
Post a Comment