Python Returns the dictionary structure code when querying MySQL

Source: Internet
Author: User
MySQLdb default query results are returned tuple, output time is not very convenient, must follow 0,1 so read, inadvertently found a simple method of modification on the Internet, is to pass a cursors. Dictcursor on the line.
Default program:
MySQLdb default query results are returned tuple, output time is not very convenient, must follow 0,1 so read, inadvertently found a simple method of modification on the Internet, is to pass a cursors. Dictcursor on the line. Default program:
Copy CodeThe code is as follows:


Import MySQLdb
db = MySQLdb.connect (host =´localhost´, user =´root´, passwd =´123456´, DB =´test´)
cursor = Db.cursor ()
Cursor.execute (´select * from Table´)
rs = Cursor.fetchall ()
Print RS


# returns similar to the following
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))
After modification:
Copy CodeThe code is as follows:


Import MySQLdb
Import Mysqldb.cursors
db = MySQLdb.connect (host =´localhost´, user =´root´, passwd =´123456´, db =´test´,cursorclass = MySQLdb.cursors.DictC Ursor)
cursor = Db.cursor ()
Cursor.execute (´select * from Table´)
rs = Cursor.fetchall ()
Print RS


# returns similar to the following
# ({' Age ': 0L, ' num ': 1000L}, {' Age ': 0L, ' num ': 2000L}, {' Age ': 0L, ' num ': 3000L}) or you can replace the Connect and cursor sections with the following
Copy CodeThe code is as follows:


db = MySQLdb.connect (host =´localhost´, user =´root´, passwd =´123456´, DB =´test´)
cursor = conn.cursor (Cursorclass = MySQLdb.cursors.DictCursor)
  • 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.