2017-09-05 66 views
0
  • 我提出了一个请求,它在json utf-8(dict与tupels)响应。
  • 我想插入到MySQL数据库的JSON响应。
  • 我使用string.encode('utf-8')对字符串进行编码,但随后数据库(也使用UTF-8编码)不会插入正确的值。

没有string.encode('utf-8')我会得到一个UnicodeEncodeError,如此看来这个必要将字符串编码mysql数据库的python3编码

UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 147: ordinal not in range(128) 

我打一个比方:在JSON

  • 字符串: 'quälend'
  • 编码后的字符串:'qu \ xC3 \ xA4lend'
  • 插入数据库:'quälend'

我的猜测是,该数据库处理编码的utf-8字符串仍然是latin-1,但是当我插入一些未编码的示例utf-8字符串时,它就起作用。所以数据库可以正确处理,但不是编码字符串。

你知道这个问题可能是什么吗?几个小时后,我对这个问题放松了下来。任何暗示高度赞赏。

回答

1

请勿使用任何编码/解码功能;只会让事情变得更糟。

ä以UTF-8(MySQL的CHARACTER SET utf8或utf8mb4)正确C3A4

ä是“Mojibake”。搜索http://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored是什么原因导致的,以及您需要做什么来避免它。

目前尚不清楚“ascii”和“latin-1”在哪里涉及;避免它们。 FC对于ü是latin1。

更多蟒蛇笔记:http://mysql.rjweb.org/doc.php/charcoll#python