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()
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
Then modify the connection code:
conn = sqlite3.connect(dbfile) cur = conn.cursor(factory=MyCursor)
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.