将python中文保存到MySQL中

时间:2016-04-23 08:58:13

标签: python mysql

我已在python中使用dict[key]=dict[key].encode('utf-8'), 并设置mysql默认字符如下:

--------------------------+--------------------------------------------------------+
| Variable_name            | Value                                                  |
+--------------------------+--------------------------------------------------------+
| character_set_client     | utf8                                                   |
| character_set_connection | utf8                                                   |
| character_set_database   | utf8                                                   |
| character_set_filesystem | binary                                                 |
| character_set_results    | utf8                                                   |
| character_set_server     | utf8                                                   |
| character_set_system     | utf8                                                   |
| character_sets_dir       | /usr/local/mysql-5.6.29-osx10.8-x86_64/share/charsets/ |
+--------------------------+--------------------------------------------------------+

但仍然无法正确使用中文,我得到的就是尘的空间。这有什么不对?

我搜索了一些答案并添加了charset="utf8 self.db=MySQLdb.connect("localhost","root","","QQ",charset="utf8")

得到错误:

(1366, "Incorrect string value: '\\xE8\\xAF\\x84\\xE8\\xAF\\xAD...' for column 'content' at row 1")

1 个答案:

答案 0 :(得分:1)

我搜索了错误1366,发现数据库排序规则与我在MySQL中放置的排序规则不匹配。所以我这样做:show full columns from table_name;找到不使用utf-8编码的行。然后alter table table_name change name name varchar(100) character set utf8 collate utf8_unicode_ci not null default '';
它有效。