python连接mysql 报'latin-1' codec can't encode character解决方法
python通过MySQLdb提交mysql数据时,如果编码设置不好会报latin-1' codec can't encode character。。。 错误
在网上找了很多方案,都比较复杂,其实如果认真研究MySQLdb目录下connections.py文件即可能了解引起这个问题的原因是因为连接建立后编码没有设置成功
解决方法其实很简单,只要连接成功后调用set_character_set('utf8') 即可
示例代码如下:
def connectToMysql(self, dbHost, dbUser, dbPsw, dbName, dbPort=3306):
try:
self.__dbConn = mysql.connect(host=dbHost, user=dbUser, passwd=dbPsw, db=dbName, port=dbPort)
self.__dbConn.set_character_set('utf8')
except Exception, e:
self.__logToFile("open mysql failed, the reason is:%s" %e)
self.__dbCursor = self.__dbConn.cursor()
self.__dbCursor.execute("set names utf8")