[英]How to print UTF-8 characters from an SQL database in Python?
我在SQL数据库(MariaDB)上有数据,其中一些包含UTF-8字符(多数为ÄÖÅ)。 在Python中打印此数据时,我没有得到正确的字符。 但是,如果我直接打印UTF-8字符(例如print("ÖÖ ää öö")
),则可以使用。
在我的.py文件中,我有# -*- coding: utf-8 -*-
;在我的.sql文件中,我有SET character_set_server = "utf8";
http://mysql.rjweb.org/doc.php/charcoll#python说
源代码中的第一行或第二行:# --编码:utf-8--
用于为字符串“ u”转储十六进制(等)的Python代码:
对于i,enumerate(u)中的c:打印i,'%04x'%ord(c),unicodedata.category(c),打印unicodedata.name(c)
关于utf8编码的其他注意事项:
⚈ db = MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME, charset="utf8", use_unicode=True)
⚈ conn = MySQLdb.connect(host="localhost", user='root', password='', db='', charset='utf8')
⚈ cursor.execute("SET NAMES utf8mb4;") -- not as good as using `charset'
⚈ db.set_character_set('utf8'), implies use_unicode=True
⚈ Literals should be u'...'
⚈ MySQL-python 1.2.4 fixes a bug wherein varchar(255) CHARACTER SET utf8 COLLATE utf8_bin is treated like a BLOB.
清单:
⚈ `# -*- coding: utf-8 -*-` -- (you have that)
⚈ `charset='utf8'` in `connect()` call -- Is that buried in `bottle_mysql.Plugin`? (Note: Try 'utf-8' and 'utf8')
⚈ Text encoded in utf8.
⚈ No need for encode() or decode() if you are willing to accept utf8 everywhere.
⚈ `u'...'` for literals
⚈ `` near start of html page
⚈ Content-Type: text/html; charset=UTF-8 (in HTTP response header)
⚈ header('Content-Type: text/html; charset=UTF-8'); (in PHP to get that response header)
⚈ `CHARACTER SET utf8 COLLATE utf8_general_ci` on column (or table) definition in MySQL.
⚈ utf8 all the way through
参考文献:
⚈ https://docs.python.org/2/howto/unicode.html#the-unicode-type
⚈ http://stackoverflow.com/questions/9154998/python-encoding-mysql
⚈ http://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
从2.0版开始,Python语言环境正式仅在内部使用UCS-2,但是“ Unicode”的UTF-8解码器会生成正确的UTF-16。 从Python 2.2开始,支持使用Unicode的“宽”版本,而改用UTF-32; [16]这些版本主要在Linux上使用。 Python 3.3不再使用UTF-16,而是根据字符串中的代码点将字符串存储在ASCII / Latin-1,UCS-2或UTF-32中的一种,并且还包括UTF-8版本因此重复转换为UTF-8的速度很快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.