Introduction to the method of returning query results in dictionary form in Python Sqlite3

高洛峰
Release: 2017-03-21 11:49:08
Original
2758 people have browsed it

SQLite3 itself does not natively provide dictionary cursors like pymysql.

cursor = conn.cursor(pymysql.cursors.DictCursor)
Copy after login

But the corresponding implementation plan has been reserved in the official documents.

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

Use this function instead of the conn.raw_factory attribute.

def dict_factory(cursor, row):  
    d = {}  
    for idx, col in enumerate(cursor.description):  
        d[col[0]] = row[idx]  
    return d  con = sqlite3.connect(":memory:") #打开在内存里的数据库
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]
Copy after login


The above is the detailed content of Introduction to the method of returning query results in dictionary form in Python Sqlite3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template