Home > Backend Development > Python Tutorial > Python implements Sqlite's method of querying fields as indexes

Python implements Sqlite's method of querying fields as indexes

WBOY
Release: 2016-08-04 08:55:39
Original
1989 people have browsed it

The example in this article describes how Python implements Sqlite to query fields as indexes. Share it with everyone for your reference, the details are as follows:

By default, the data obtained from sqlite is digitally indexed. During the development stage, the database is often modified, so it is inconvenient. In fact, there is a solution in the python source code. I directly read the source code of sqlite3 and explored some. The solution is as follows :

If you connect by default, use the following code, which is indexed by numbers:

conn = sqlite3.connect(dbfile)
cur = conn.cursor()

Copy after login

In order to make the obtained result set use the field as the index, you need to add a function and a class:

def dict_factory(cursor, row):
  d = {}
  for idx, col in enumerate(cursor.description):
    d[col[0]] = row[idx]
  return d
class MyCursor(sqlite3.Cursor):
  def __init__(self, *args, **kwargs):
    sqlite3.Cursor.__init__(self, *args, **kwargs)
    self.row_factory = dict_factory

Copy after login

Then modify the connection code:

conn = sqlite3.connect(dbfile)
cur = conn.cursor(factory=MyCursor)

Copy after login

What is read after that is indexed by the field.

Readers who are interested in more Python-related content can check out the special topics on this site: "Summary of common database operation skills in Python", "Python data structure and algorithm tutorial", "Summary of Python Socket programming skills", "Summary of Python function usage skills" , "A Summary of Python String Operation Skills", "A Classic Tutorial for Getting Started with Python" and "A Summary of Python File and Directory Operation Skills"

I hope this article will be helpful to everyone in Python programming.

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