Python 从 MySQL 数据库打印错误的编码
Python prints wrong encoding from MySQL database
从 MySQL 数据库调用数据时,我的 Python 出现问题。
数据库设置为 UTF-8 并包含特殊字母,例如“Æ”和“Ø”。
这是我用来从 Table
调用用户名的代码
# -*- coding: UTF-8 -*-
import pymysql
db = pymysql.connect(
host="localhost",
user="root",
password="XXXXXXXX",
db="pythonconnectiontest",
charset="utf8"
)
cursor = db.cursor()
cursor.execute("SELECT Username FROM Account")
numrows = cursor.rowcount
for i in range (numrows):
row = cursor.fetchone()
print row
预期输出为:
ThisTextIsBrøken
Tæst
Word
实际输出:
(u'ThisTextIsBr\xf8ken',)
(u'T\xe6st',)
(u'Word',)
我确实知道值前面的 'U' 表示这是 UNICODE,我可能只需要 python 使用 encode() 或 decode() 正确解释文本.
我花了很多时间试图解决这个问题,解决方案可能非常简单。
希望有人能帮我解决这个问题。
感谢阅读。
它输出的 unicode 字符串完全没问题。您可以通过在 python shell:
中尝试 print u'ThisTextIsBr\xf8ken'
来验证这一点
➜ python2
Python 2.7.15 (default, Jan 10 2019, 23:20:52)
[GCC 8.2.1 20181127] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'ThisTextIsBr\xf8ken'
ThisTextIsBrøken
您的困惑仅仅是关于 python 如何表示包装在另一个对象中的 unicode 字符串。在这种情况下,您的每行代表一个 tuple
列或更具体地说是一个包含单个 unicode 字符串的元组。
您可以通过调整代码来打印实际的 unicode 字符串而不是包含它的元组来验证这一点。
# -*- coding: UTF-8 -*-
import pymysql
db = pymysql.connect(
host="localhost",
user="root",
password="XXXXXXXX",
db="pythonconnectiontest",
charset="utf8"
)
cursor = db.cursor()
cursor.execute("SELECT Username FROM Account")
numrows = cursor.rowcount
for i in range (numrows):
row = cursor.fetchone()
print row[0]
现在应该会输出预期的字符串。
从 MySQL 数据库调用数据时,我的 Python 出现问题。
数据库设置为 UTF-8 并包含特殊字母,例如“Æ”和“Ø”。
这是我用来从 Table
调用用户名的代码# -*- coding: UTF-8 -*-
import pymysql
db = pymysql.connect(
host="localhost",
user="root",
password="XXXXXXXX",
db="pythonconnectiontest",
charset="utf8"
)
cursor = db.cursor()
cursor.execute("SELECT Username FROM Account")
numrows = cursor.rowcount
for i in range (numrows):
row = cursor.fetchone()
print row
预期输出为:
ThisTextIsBrøken
Tæst
Word
实际输出:
(u'ThisTextIsBr\xf8ken',)
(u'T\xe6st',)
(u'Word',)
我确实知道值前面的 'U' 表示这是 UNICODE,我可能只需要 python 使用 encode() 或 decode() 正确解释文本.
我花了很多时间试图解决这个问题,解决方案可能非常简单。
希望有人能帮我解决这个问题。
感谢阅读。
它输出的 unicode 字符串完全没问题。您可以通过在 python shell:
中尝试print u'ThisTextIsBr\xf8ken'
来验证这一点
➜ python2
Python 2.7.15 (default, Jan 10 2019, 23:20:52)
[GCC 8.2.1 20181127] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'ThisTextIsBr\xf8ken'
ThisTextIsBrøken
您的困惑仅仅是关于 python 如何表示包装在另一个对象中的 unicode 字符串。在这种情况下,您的每行代表一个 tuple
列或更具体地说是一个包含单个 unicode 字符串的元组。
您可以通过调整代码来打印实际的 unicode 字符串而不是包含它的元组来验证这一点。
# -*- coding: UTF-8 -*-
import pymysql
db = pymysql.connect(
host="localhost",
user="root",
password="XXXXXXXX",
db="pythonconnectiontest",
charset="utf8"
)
cursor = db.cursor()
cursor.execute("SELECT Username FROM Account")
numrows = cursor.rowcount
for i in range (numrows):
row = cursor.fetchone()
print row[0]
现在应该会输出预期的字符串。