Home >Database >Mysql Tutorial >How to Import a MySQL Table into a List of Dictionaries in Python Using mysqldb?

How to Import a MySQL Table into a List of Dictionaries in Python Using mysqldb?

DDD
DDDOriginal
2024-12-02 14:37:12376browse

How to Import a MySQL Table into a List of Dictionaries in Python Using mysqldb?

Python: Importing MySQL Table into Dictionary Using mysqldb

Importing a MySQL table as a list of dictionary objects in Python is a convenient way to work with database data. Here's how you can achieve this using the mysqldb library:

To begin, establish a connection to your MySQL database using the mysqldb.connect() function. For ease of use, pass the DictCursor class as the cursor parameter. This will enable the use of a cursor that returns rows as dictionaries:

import MySQLdb.cursors
connection = MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)

Next, create a cursor object from the established connection. Execute a query to fetch the data from the desired table:

cursor = connection.cursor()
cursor.execute("SELECT * FROM my_table")

Fetch the returned rows as a list of dictionaries using the cursor's fetchall() method:

rows = cursor.fetchall()

Finally, store the fetched rows in a list named 'data':

data = rows

This 'data' list now contains a collection of dictionaries, each representing a row from the MySQL table. You can access the column values by referencing the dictionary keys:

for row in data:
    print(row['column_name'])

The above is the detailed content of How to Import a MySQL Table into a List of Dictionaries in Python Using mysqldb?. 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