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
Release: 2024-12-02 14:37:12
Original
459 people have browsed it

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)
Copy after login

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")
Copy after login

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

rows = cursor.fetchall()
Copy after login

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

data = rows
Copy after login

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'])
Copy after login

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!

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