我在使用Python从MySQL数据库读取utf-8数据时遇到问题。我的数据库包含一个名为Videos的表,并且该表至少包含一行具有Unicode字符,即[KR] Samsung Galaxy Beam 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
不会继续到下一排。
我使用的是PhpMyAdmin版本4.1.14、MySQL版本5.6.17和Python版本2.7.8。
编辑:我删除了except子句,并更新了出现的错误。