Python operation mysql Chinese show garbled code solution

  • 2020-04-02 14:14:15
  • OfStack

This example shows a script python used to transform the table configuration data XML and generate the corresponding parsing code.
But in the Chinese code on the emergence of garbled code, will now share the solution for your reference.

Specific methods are as follows:

1. Python file set encoding utf-8 (#encoding=utf-8)
2. MySQL database charset=utf-8
3. Python connection to MySQL is with the parameter charset=utf8
4. Set the default coding of Python to utf-8 (sys.setdefaultencoding(utf-8))

The sample code is as follows:

#encoding=utf-8
 
import sys
import MySQLdb as mdb
 
reload(sys)
sys.setdefaultencoding('utf-8')
 
con = None
 
try:
    con = mdb.Connect('localhost','root','jobin','zmld',charset='utf8')
    cur = con.cursor()
    cur.execute("show full columns from player")
 
    numRows = int(cur.rowcount)
 
    for i in range(numRows):
        row = cur.fetchone()
        comment = row[len(row) - 1]
        print comment
finally:
    if con:
        con.close()

I hope this article has helped you with your Python programming.


Related articles: