Python gets a question mark or garbled character in the Chinese data output in UTF8 format from the database

Source: Internet
Author: User

I use Python to operate the MySQL database, the data format of the database is UTF8, I use Python to invoke the SELECT statement after the database to obtain information, and then print out the use of printing, the original Chinese data can not be displayed, the display is a string? , in order to solve this problem, I also racked my brains.

I collected a lot of information on the Internet, everyone said that Windows default format is ' GBK ', the output from the MySQL database to obtain the Chinese data, it is necessary to write:

Assume that info is the Chinese value from the database, print info.decode (' UTF-8 '). Encode (' GBK ')

Results:


But, did I try this many times or not solve the problem, or output? , it is also argued that the encoding format is passed in when the database is linked

db = MySQLdb.connect (' localhost ', ' root ', ', ' Zou ', 3306,' UTF8 ')

Results:

     

This is still not the expected effect, but he did not appear this time? , but has become garbled, but here the words have been moving in a good direction.


In the end, I combined the above two viewpoints to achieve the purpose ^_^

Take a look at my code:


This time look at the results of the program running:


OK, problem solved!

Python gets a question mark or garbled character in the Chinese data output in UTF8 format from the database

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.