Django向MySQL中插入汉字出错后的解决方法

OS Version: Kubuntu 17.04.1

MySQL Version: 5.7.18

Django Version: 1.8.0

http://code.ziqiangxuetang.com/django/django-admin.html  <--- 按照涂老师的教程学习django的 admin 部分时,runserver 后登陆 /admin 页面,添加 article,发现报错,如下:

OperationalError at /admin/blog/article/add/

(1366, "Incorrect string value: '\\xE6\\xA0\\x87\\xE9\\xA2\\x98' for column 'title' at row 1")
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/blog/article/add/
Django Version: 1.8
Exception Type: OperationalError
Exception Value:
(1366, "Incorrect string value: '\\xE6\\xA0\\x87\\xE9\\xA2\\x98' for column 'title' at row 1")
Exception Location: /home/dechao/my_python/ziqiangxuetang/zq_env/local/lib/python2.7/site-packages/MySQLdb/connections.py in defaulterrorhandler, line 36
Python Executable: /home/dechao/my_python/ziqiangxuetang/zq_env/bin/python
Python Version: 2.7.13
Python Path:
['/home/dechao/my_python/ziqiangxuetang/zqadmin',
 '/home/dechao/my_python/ziqiangxuetang/zq_env/lib/python2.7',
 '/home/dechao/my_python/ziqiangxuetang/zq_env/lib/python2.7/plat-x86_64-linux-gnu',
 '/home/dechao/my_python/ziqiangxuetang/zq_env/lib/python2.7/lib-tk',
 '/home/dechao/my_python/ziqiangxuetang/zq_env/lib/python2.7/lib-old',
 '/home/dechao/my_python/ziqiangxuetang/zq_env/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/home/dechao/my_python/ziqiangxuetang/zq_env/local/lib/python2.7/site-packages',
 '/home/dechao/my_python/ziqiangxuetang/zq_env/lib/python2.7/site-packages']
Server time: 星期三, 12 七月 2017 06:41:01 +0000

解决思路:

查看数据库字符集   show variables like 'character%';

发现 character-set-server 和  character_set_database 的值为latin1

解决方案:

编辑  /etc/mysql/mysql.conf.d/mysqld.cnf    在[mysqld]下添加  character-set-server=utf8

systemctl restart mysql  重启 MySQL Server,再此查看字符集变量,发现已经是utf8,drop database myblog 并 create database myblog

问题解决!


你可能感兴趣的:(Python,学习杂记)