簡體   English   中英

如何在Python中從SQL數據庫打印UTF-8字符?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM