Home  >  Article  >  Database  >  How to Import MySQL Table Data as a Python Dictionary Using mysqldb?

How to Import MySQL Table Data as a Python Dictionary Using mysqldb?

DDD
DDDOriginal
2024-11-19 19:29:02358browse

How to Import MySQL Table Data as a Python Dictionary Using mysqldb?

Importing MySQL Table Data as a Dictionary Using Python and mysqldb

For efficient data handling in Python, it can be beneficial to import data from a MySQL database as a list of dictionary objects. Here's a helpful solution using the mysqldb library:

Solution:

To achieve this, mysqldb offers a specific cursor class called DictCursor. By specifying this cursor class while establishing the database connection, you can retrieve result rows as dictionaries:

import MySQLdb.cursors

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

With the connection established, execute the SQL query to fetch the rows from the table:

cursor = db.cursor()
cursor.execute("SELECT * FROM table_name")

The fetched rows can now be iterated over and accessed as dictionaries:

data = []
for row in cursor:
    data.append(row)

This will result in a list of dictionary objects, similar to the example you provided:

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ]

The above is the detailed content of How to Import MySQL Table Data as a Python Dictionary 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