Methods for returning MySQL query results to dictionary types in Python

Source: Internet
Author: User
Tags mysql query utf 8

Python's MySQLdb module is a python-connected MySQL module, and the default query results are returned as a tuple type, which can only be accessed through 0,1. Index Access data
Default Connection database:

MySQLdb.connect (Host=host, User=user, passwd=passwd, Db=db, Port=port, charset= ' UTF 8 ')

Copy Code Print:

Copy the code code as follows for the row in Data:print type (row) print row


Execution Result:

Copy Code

The code is as follows: <type ' tuple ' > (1L,)


is a tuple type.
We can do this. Causes the data query result to return the dictionary type, that is, the field = Data
import module

Import Mysqldb.cursors


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

MySQLdb.connect (Host=host, User=user, passwd=passwd, Db=db, Port=port, charset= ' UTF 8 ', Cursorclass = MySQLdb.cursors.DictCursor)

Rerun the script to see the results of the execution:

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


Get!
Note that if the port is to be specified, the value must be integer if it is connected, otherwise an error will occur!

Methods for returning MySQL query results to dictionary types in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.