首页 > 解决方案 > Python 和 mySQL UnicodeDecodeError:“ascii”编解码器无法解码字节

问题描述

我真的需要你的帮助

我正在使用简单的 python 脚本从 mysql DB 中导出数据。但是,当我打印结果时,我在其中一个字段中得到了一些 UTF-8 字符,当我使用制表符打印它时,它给了我以下流行错误“UnicodeDecodeError:'ascii'编解码器无法解码字节”主要目标是打印数据库上的确切数据。

你建议如何解决这个问题?

任何帮助将不胜感激谢谢

编码:

# -*- coding: utf-8 -*-

mydb = mysql.connector.connect(
  host="localhost",
  user="user",
  password="password",
  database="database",
  #charset='ascii' -> if i use this i can print with tabulate but some characters are replaced with ?
)

mycursor = mydb.cursor()
mycursor.execute("SELECT column1, column2, column3, column4, column5, column6, column7, column8, column9, column10, colum11 FROM database LIMIT 5")

myresult = mycursor.fetchall()

for x in myresult:
    print ('\n')
    print(x)  # Here i can print the results with for example "Situa\xc3\xa7\xc3\xa3o com impacto em monitoria e despiste"

print(tabulate(myresult, headers=['column1', 'column2', 'column3', 'column4', 'column5', 'column6', 'column7', 'column8', 'column9', 'column10', 'colum11'], tablefmt='psql')) 
# And here i get the error "... UnicodeDecodeError: 'ascii' codec can't decode byte... "

标签: pythonmysqlunicodeutf-8ascii

解决方案


推荐阅读