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!