Mapping result rows to namedtuple in python sqlite

前端 未结 3 1136
说谎
说谎 2020-12-31 06:42

I am playing a bit with the python api for sqlite3, i have a little table for store languages with an id, name and creation_date fields. I am trying to map the raw query res

3条回答
  •  借酒劲吻你
    2020-12-31 07:14

    An improved row_factory is actually this, which can be reused for all sorts of queries:

    from collections import namedtuple
    
    def namedtuple_factory(cursor, row):
        """Returns sqlite rows as named tuples."""
        fields = [col[0] for col in cursor.description]
        Row = namedtuple("Row", fields)
        return Row(*row)
    
    conn = sqlite3.connect(":memory:")
    conn.row_factory = namedtuple_factory
    cur = con.cursor()
    

提交回复
热议问题