Home >Backend Development >Python Tutorial >Introduction to the method of returning query results in dictionary form in Python Sqlite3

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

高洛峰
高洛峰Original
2017-03-21 11:49:082781browse

SQLite3 itself does not natively provide dictionary cursors like pymysql.

cursor = conn.cursor(pymysql.cursors.DictCursor)

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

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"]


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!

Statement:
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