如何使用Python从mysql数据库获取并打印utf-8数据?
我在使用Python从MySQL数据库读取utf-8数据时遇到问题。我的数据库包含一个名为Videos
一个表,表中包含至少一排有Unicode的字符,即如何使用Python从mysql数据库获取并打印utf-8数据?
[KR]三星Galaxy梁2간단리뷰[4K]
的排序规则表格是utf8_general_ci
,就像表格中字段的排序规则一样。
这是我以从我的表中获取所有数据写的代码:
# Open database connection
db = MySQLdb.connect("localhost","matan","pass","youtube", charset = 'utf8',use_unicode=True)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM VIDEOS"
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
title = row[0]
link = row[1]
# Now print fetched result
print ("title=%s\nlink=%s\n\n" % \
(title, link))
except:
print "Error: unable to fecth data"
# disconnect from server
db.close()
当我运行上面的代码,它打印所有只包含“ASCII”字符的行,但是当它获取包含Unicode字符(即我上面提到的线)的行,它打印:
File "C:\Users\Matan\Dropbox\Code\Python\youtube.py", line 28, in printall (title, link)) File "C:\Python27\lib\encodings\cp862.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode characters in position 33-34: c haracter maps to <undefined>
,不继续下一行。
我使用的是PhpMyAdmin版本4.1.14,MySQL版本5.6.17和Python版本2.7.8。
编辑:我删除了except子句,并更新了我得到的错误。
您的问题是与您的终端(sys.stdout
)编码(cf http://en.wikipedia.org/wiki/Code_page_862),这取决于您的系统的设置。最好的解决方案(如此处所述:https://stackoverflow.com/a/15740694/41316)是在将您的unicode数据打印到sys.stdout
之前对其进行明确编码。
如果你不能使用更可用的编码(UTF-8想起来,因为它已经被设计为处理所有的Unicode字符),你至少可以使用替代错误处理,如“替换”(替换非用'?')或“忽略”(禁止不可编码的字符)。
这是你的代码的修正版本,你可以用encoding
和on_error
设定扮演找出解决方案适用于您:
import sys
import MySQLdb
# set desired output encoding here
# it looks like your default encoding is "cp862"
# but you may want to first try 'utf-8' first
# encoding = "cp862"
encoding = "utf-8"
# what do when we can't encode to the desired output encoding
# options are:
# - 'strict' : raises a UnicodeEncodeError (default)
# - 'replace': replaces missing characters with '?'
# - 'ignore' : suppress missing characters
on_error = "replace"
db = MySQLdb.connect(
"localhost","matan","pass","youtube",
charset='utf8',
use_unicode=True
)
cursor = db.cursor()
sql = "SELECT * FROM VIDEOS"
try:
cursor.execute(sql)
for i, row in enumerate(cursor):
try:
# encode unicode data to the desired output encoding
title = row[0].encode(encoding, on_error)
link = row[1].encode(encoding, on_error)
except UnicodeEncodeError as e:
# only if on_error='strict'
print >> sys.stderr, "failed to encode row #%s - %s" % (i, e)
else:
print "title=%s\nlink=%s\n\n" % (title, link))
finally:
cursor.close()
db.close()
注意:您可能还需要阅读本(特别评论)http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/更多关于Python,字符串,unicode,编码,sys.stdout
和终端问题。
如果你真的想知道出了什么问题,首先摆脱这个无用的裸体except子句,让真正的异常传播。然后请回来并发布完整的回溯。只是为了记录:因为您将'use_unicode = True'传递给您的连接,所以您从数据库返回的所有数据都是unicode字符串(类型为“Unicode”,而不是“str”类型)。您必须在打印之前将它们编码为正确的编码(正确的编码与系统相关)。 – 2014-12-03 16:05:22
我用你的建议编辑了我的问题。谢谢。 – matan89 2014-12-03 17:01:52