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