解决方案:在Python连接MySQL时,确保统一使用UTF-8编码。连接字符串添加charset='utf8mb4',代码示例:import pymysql conn = pymysql.connect(host='localhost', user='root', password='123456', db='test', charset='utf8mb4') cursor = conn.cursor() cursor.execute('set names utf8mb4')。插入数据前确保字符串是unicode,读取时print(result.decode('utf-8'))。MySQL配置文件my.cnf中设置[client] default-character-set=utf8 [mysql] default-character-set=utf8 [mysqld] character-set-server=utf8 collation-server=utf8_general_ci。
第一篇来源内容
在使用Python操作MySQL数据库时,经常遇到中文乱码的问题。这是因为Python和MySQL的字符编码不一致造成的。解决办法是:在建立连接时指定字符集为utf8。代码如下:conn = MySQLdb.connect(host='localhost',user='root',passwd='sa',db='test',charset='utf8')。另外,在执行SQL语句前,执行set names utf8。
第二篇来源内容
Python连接MySQL插入中文乱码,查询也乱码。原因:MySQL默认latin1,Python3默认utf8。解决:1.修改my.cnf [mysqld] default-character-set=utf8mb4 character-set-server=utf8mb4 collation-server=utf8mb4_general_ci [mysql] default-character-set=utf8mb4 [client] default-character-set=utf8mb4。2.Python代码:conn= pymysql.connect(...,charset='utf8mb4') cursor.execute("SET NAMES utf8mb4;")。
第三篇来源内容
攻克Python MySQL中文乱码:统一编码到UTF-8。步骤:1、重启MySQL服务前修改my.cnf文件,添加default-character-set=utf8。2、进入MySQL执行ALTER DATABASE yourdb CHARACTER SET utf8 COLLATE utf8_general_ci;。3、Python连接时conn = pymysql.connect(charset='utf8')。4、表创建时指定ENGINE=InnoDB DEFAULT CHARSET=utf8。
第四篇来源内容
Python操作MySQL中文乱码终极解决:import sys reload(sys) sys.setdefaultencoding('utf-8') #Python2用。连接:db = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123",db="test",port=3306,charset="utf8")。插入:cursor.execute("insert into t1 values(%s,%s)",(u'中文测试'.encode('utf8'),'value'))。
第五篇来源内容
简单三步搞定MySQL+Python中文乱码:1.修改/etc/my.cnf [client] default-character-set = utf8 [mysql] default-character-set = utf8 [mysqld] default-character-set = utf8。2.重启mysqld服务。3.Python代码中:connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8')。
第六篇来源内容
使用pymysql时,连接参数charset='utf8mb4',并且在cursor执行后立即cursor.execute('SET NAMES utf8mb4;')。读取数据时用cursor.fetchall(),然后for row in rows: print(''.join(str(x) for x in row))。避免decode,直接用Python3的str。
Q: 为什么Python插入MySQL中文会乱码?
A: 因为MySQL表或连接字符集不是utf8,而Python发送utf8数据不匹配。
Q: 如何永久设置MySQL编码?
A: 编辑my.cnf文件设置default-character-set=utf8mb4,重启服务。
Q: Python3和Python2乱码解决一样吗?
A: Python3默认unicode,连接加charset='utf8mb4'即可;Python2需sys.setdefaultencoding('utf-8')。
Q: utf8和utf8mb4区别?
A: utf8mb4支持更多emoji和特殊字符,推荐用utf8mb4。