Home > Database > Mysql Tutorial > body text

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

DDD
Release: 2024-11-19 19:29:02
Original
367 people have browsed it

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

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

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

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

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

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

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!

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