📜  python sqlite3 dict from query (1)

📅  最后修改于: 2023-12-03 15:34:04.738000             🧑  作者: Mango

Python SQLite3 Dict from Query

Python SQLite3 is a built-in module that enables us to work with the SQLite database from Python. SQLite is a database engine written in C that explains why it's fast, robust and lightweight.

In this tutorial, we will cover how to fetch results from SQLite and use the dictfetchall() function to return a dictionary instead of the default tuple.

Requirements

First, ensure that you have sqlite3 and os modules installed. Use the pip command to install the modules if they are not installed.

pip install sqlite3
pip install os
Connect to the Database

It's time to connect to the SQLite database using the connect() method. Pass the path of the database in the connect() method to establish a connection to the database.

import sqlite3

connection = sqlite3.connect("sample.db")
Defining the dictfetchall() Function

The dictfetchall() function maps the column name to their corresponding values. The function fetches all the rows from the database and returns a list of dictionaries.

def dictfetchall(cursor):
    """Returns all rows from a cursor as a list of dicts"""
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]
Executing SQL Query

Use the execute() method to execute SQL queries. Afterward, use the fetchall() method to fetch all the rows from the query result.

cursor = connection.cursor()
cursor.execute("SELECT * FROM PERSON")
rows = cursor.fetchall()

result = dictfetchall(cursor)
The Complete Code
import sqlite3

connection = sqlite3.connect("sample.db")

def dictfetchall(cursor):
    """Returns all rows from a cursor as a list of dicts"""
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]

cursor = connection.cursor()
cursor.execute("SELECT * FROM PERSON")
rows = cursor.fetchall()

result = dictfetchall(cursor)
Conclusion

In summary, we have learned how to fetch results from SQLite and use the dictfetchall() function to return a dictionary instead of a tuple.