"MySQL" MySQLdb Return dictionary method

Source: Internet
Author: User

Source: http://blog.csdn.net/zgl_dm/article/details/8710371

The default MySQLdb returns a tuple, which is not friendly to the user and is not conducive to maintenance
Here's how it's resolved

ImportMySQLdbImportMysqldb.cursorsconn=MySQLdb.connect (Host='localhost', user ='Root', passwd="', db ='Test', compress = 1, Cursorclass= MySQLdb.cursors.DictCursor, charset='UTF8')//<-Importantcursor=conn.cursor () cursor.execute ("SELECT name, txt from table") Rows=Cursor.fetchall () cursor.close () Conn.close ()

For row in rows:
Print row [' name '], row [' txt '] # bingo!

# another (even better) is:

conn =MySQLdb. Connect (Host='localhost', user ='Root', passwd="', db ='Test', compress = 1) Cursor= Conn.cursor (Cursorclass =MySQLdb.cursors.DictCursor)# ...#Results by field namecursor =conn.cursor ()# ...#... results by field number

Note: If the Pymysql and Mysql-python libraries are installed at the same time, it will cause Mysql-python to fail, only pymsql available

"MySQL" MySQLdb Return dictionary method

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.