Sqlite and Python — return a dictionary using fetchone()?

后端 未结 8 1793
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 04:03

I\'m using sqlite3 in python 2.5. I\'ve created a table that looks like this:

   create table votes (
      bill text,
      senator_id text,
      vote text)
<         


        
8条回答
  •  悲&欢浪女
    2021-01-31 04:28

    The way I've done this in the past:

    def dict_factory(cursor, row):
        d = {}
        for idx,col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d
    

    Then you set it up in your connection:

    from pysqlite2 import dbapi2 as sqlite
    conn = sqlite.connect(...)
    conn.row_factory = dict_factory
    

    This works under pysqlite-2.4.1 and python 2.5.4.

提交回复
热议问题