Python Sqlite3 How to return query results in a dictionary _python

Source: Internet
Author: User

The sqlite3 itself does not natively provide a dictionary-like cursor as pymysql.

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

But the official document has already reserved the corresponding implementation plan.

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

Use this function instead of the Conn.raw_factory property.

con = Sqlite3.connect (": Memory:") #打开在内存里的数据库
con.row_factory = dict_factory
cur = con.cursor ()
Cur.execute ("Select 1 as a")
print Cur.fetchone () ["a"]

Official Document Links

The above is a small series for everyone to bring Python Sqlite3 in the dictionary form to return the results of the implementation of the query all the content, I hope that we support cloud Habitat Community ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.