python - 如何在Python中从SQL数据库打印UTF-8字符?

标签 python mysql encoding utf-8 mariadb

我在 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代码:

对于 enumerate(u) 中的 i、c: print 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.

list :

⚈  `# -*- 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

Python语言环境从2.0版本开始正式在内部只使用UCS-2,但是UTF-8解码器到“Unicode”会产生正确的UTF-16。自 Python 2.2 起,支持使用 UTF-32 替代“宽”版本的 Unicode;[16] 这些主要在 Linux 上使用。 Python 3.3 不再使用 UTF-16,而是将字符串存储为 ASCII/Latin-1、UCS-2 或 UTF-32 之一,具体取决于字符串中的代码点,还包括 UTF-8 版本因此重复转换为 UTF-8 的速度很快。

关于python - 如何在Python中从SQL数据库打印UTF-8字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33902693/

相关文章:

python - 使用 Windows 在 Sublime Text 的控制台中打印 utf8 字符串

encoding - 为什么Jedis不能 'get'输出redis-cli.exe设置的中文字符?

python - 查找给定字符串是python中的单词,字符还是数字

使用附加参数包装函数并更改输出的 Pythonic 方式

php - mysql连接两个不同的表

mysql - SQL 语句中截断不正确的 DOUBLE 值错误?

python - 在 Python 中读取大文件

python - Django 任务、提醒、通知

mysql - 从 GROUP BY 中获取 MAX

Python - 读取奇怪的 utf-16 格式的文本文件