I'm having problems with reading utf-8 data from a MySQL DB using Python. My DB contains one table named Videos
, and the table contains at least one row that has Unicode chars, i.e.
[KR] Samsung Galaxy Beam 2 간단 리뷰 [4K]
The collation of the table is utf8_general_ci
, just like the collation of the fields in the table.
This is the code I wrote in order to fetch all the data from my table:
# 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()
When I run the above code, it prints all the rows that contain only "ascii" chars, but when it gets to a row that contains Unicode char (i.e. the line I mentioned above), it prints :
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>
and doesn't continue to the next row.
I'm using PhpMyAdmin version 4.1.14, MySQL version 5.6.17, and Python version 2.7.8 .
Edit: I dropped the except clause, and updated the error I've got.