Method in Python to have the MySQL query result return a dictionary type

  • 2020-04-02 13:57:31
  • OfStack

Python's MySQLdb module is a module for Python to connect to MySQL. The default query result is returned as a tuple type, which can only be accessed through 0,1.. Equal index subscripts access data
Default connection to database:


MySQLdb.connect(
    host=host,
        user=user,
        passwd=passwd,
        db=db,
        port=port,
        charset='utf8'
)

Query data:

cur = conn.cursor()
cur.execute('select b_id from blog limit 1')
data = cur.fetchall() 
cur.close()
conn.close()

Print:

for row in data:
    print type(row)
    print row

Execution results:

<type 'tuple'>
(1L,)

Is of type tuple.
We can do this so that the result of the data query returns the dictionary type, that is, the field = data
The import module

import MySQLdb.cursors

Add this parameter to the join function   Cursorclass = MySQLdb. Your cursors. DictCursor such as:

MySQLdb.connect(
    host=host,
        user=user,
        passwd=passwd,
        db=db,
        port=port,
        charset='utf8',
    cursorclass = MySQLdb.cursors.DictCursor
)

Rerun the script to see the results:

<type 'dict'>
{'b_id': 1L}

Done!
Note that the port must be an integer if it is specified during the connection, otherwise an error will occur!


Related articles: