Solve the problem of Python operation MySQL Chinese garbled

Source: Internet
Author: User

Original code:

ImportOS, sys, stringImportMysqldbmysql_host='localhost'Mysql_port='3306'Mysql_user='Root'Mysql_pass="'mysql_db='app_hwms'defMain ():Try: Conn= MySQLdb.connect (Host=mysql_host,user=mysql_user, passwd=mysql_pass,db=mysql_db)exceptException, E:Printe sys.exit () C=conn.cursor () text= u'English'    PrintText C.execute ("INSERT into test values ('%s ')"%(text)) C.execute ('SELECT * FROM Test') msgs=list (C.fetchall ())Printmsgsif __name__=='__main__': Main ()

The following error occurred:

and the direct operation of MySQL:

It's in Chinese.

Workaround:

1 python file Set encoding utf-8 (file front plus #encoding =utf-8)
2 python connection mysql is plus parameter Charset=utf8

3 Set Python's default encoding to Utf-8 (sys.setdefaultencoding (Utf-8)

Modified code:

#Encoding=utf-8ImportOS, sys, stringImportMysqldbmysql_host='localhost'Mysql_port='3306'Mysql_user='Root'Mysql_pass="'mysql_db='app_hwms'Reload (SYS) sys.setdefaultencoding ('Utf-8')defMain ():Try: Conn= MySQLdb.connect (Host=mysql_host,user=mysql_user, passwd=mysql_pass,db=mysql_db,charset='UTF8')    exceptException, E:Printe sys.exit () C=conn.cursor () text= u'English'    PrintText C.execute ("INSERT into test values ('%s ')"%(text)) C.execute ('SELECT * FROM Test') msgs=list (C.fetchall ())Printmsgsif __name__=='__main__': Main ()

Results of the re-execution:

And with flask, in the HTML of the original display?? Chinese characters can also be displayed correctly.

Solve the problem of Python operation MySQL Chinese garbled

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.