Python MySQLdb returns a dictionary result set with the database field name as the key value.

Source: Internet
Author: User

The result set queried using Python MySQLdb is in the form of an array. The access format is an array format, that is:

#... Connect to the database
SQL = 'SELECT. id,. group,. name, a.apk _ id,. ipa_id, B. name as ipa_name, c. name as apk_name from product a left join file_info B on. ipa_id = B. id left join file_info c on a.apk _ id = c. id ;'
Conn = MySQLdb. connect (host = "localhost", user = "atool", passwd = "atool", db = "atool", charset = "utf8 ")
Cursor = conn. cursor ()
 
N = cursor.exe cute (SQL)
R = cursor. fetchall ()
For p in app_info:
Try:
Print ('Project % d' % p [0])
Failed T Exception, ex:
Print Exception, ":", ex
Continue

The access method uses the array index [0] for access, which is difficult to understand and inconvenient. This can be customized in PHP.


Array PDOStatement: fetchAll ([int $ fetch_style [, mixed $ fetch_argument [, array $ ctor_args = array ()])

You can use fetch_style to configure the subscript of a practical array, or under the database field name, or both.

In fact, Python MySQLdb can also be configured, but the configuration is not in the fetch result set, but when the database gets the cursor after the connection, specify a cursor type as the dictionary format. The following code is used:

Conn = MySQLdb. connect (host = "localhost", user = "atool", passwd = "atool", db = "atool", charset = "utf8 ")
Cursor = conn. cursor (cursorclass = MySQLdb. cursors. DictCursor)

Test the code to see the code effect! Enjoy ~

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.