版权声明:转载注明出处,大家一起交流 https://blog.csdn.net/qq_38231051/article/details/81334702
环境:
centos7+mysql5.7.22+pythen3.6+pymysql
设置mysql编码:
--在 [mysql] 标签下加上一行
default-character-set = utf8
--在 [mysql.server]标签下加上一行
default-character-set = utf8
--在 [mysqld_safe]标签下加上一行
default-character-set = utf8
--在 [client]标签下加上一行
default-character-set = utf8
重启服务:service mysql restart
查看设置结果:show variables like "%character%";
pymysql设置:
在往数据库中写入时
连接时加入charset='utf8'字段
读数据库中的数据:
连接时不加charset字段;
但要加:
cur.execute('SET CHARACTER SET utf8;')
或者
cur.execute('SET NAMES utf8;')
代码实例:
写数据库时在connect中加入charset='utf8'字段;
#-*- coding=utf-8 -*-
import pymysql
#读数据库:
db = pymysql.connect(host='127.0.0.1',user='root',password='1234',db='test_db',port=3306)
cur = db.cursor()
sql = """select * from test"""
#cur.execute('SET NAMES utf8;')
cur.execute('SET CHARACTER SET utf8;')
try:
cur.execute('SET character_set_connection=utf8;')
ex = cur.execute(sql)
books = cur.fetchmany(ex)
for book in books:
print(book[1])
except Exception as e:
raise e
finally:
db.close()