【问题标题】:Error Reading unicode word from MySQL [duplicate]从 MySQL 读取 unicode 字时出错 [重复]
【发布时间】:2017-06-13 03:43:04
【问题描述】:

我是 python 新手,从 mysql 读取数据时遇到问题。在 mysql 中,我的表存储目的地:

    |id  | Destination|
    |1   |Hà Nội      |
    |2   |Hồ Chí Minh |

... 但是当我从 python 中读取它时,它会返回:' u\'H\xe0 N\u1ed9i\'' for Hà Nội。有什么方法可以将其转换回原始字符串:'Hà Nội' 这是我打开连接和选择数据的代码:

def __init__(self):
    self.mySQLConnection = mysql.connector.connect(user='root', password='', host='localhost',database='traveltrend',charset='utf8',use_unicode=True)
    self.cursor = self.mySQLConnection.cursor(buffered=True)

 def getDest(self):
    self.cursor.execute("SELECT ID, ThanhPho FROM diadiem ")
    row = self.cursor.fetchone()
    listDest={}
    while row is not None:
        request = str(row)
        request = request.strip('()')
        request = request.split(',')
        encoding = "utf-8"
        on_error = "replace"
        place= request[1].encode(encoding,on_error)

【问题讨论】:

  • 你能发布你用来创建表的查询吗?
  • 我使用 php 我的管理员创建表,但这里是生成的 sql 代码 CREATE TABLE destination ( ID int(11) NOT NULL, ThanhPho varchar(50) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL ) ENGINE=MyISAM 默认字符集=utf8mb4 COLLATE=utf8mb4_vietnamese_ci; @arun

标签: python mysql unicode


【解决方案1】:

我连接 MySQLdb 包。我用 unicode 字符从 MySQL 读取,这对我有用。

from MySQLdb import connect
connection = connect(user='root', passwd='', host='localhost',db='traveltrend',use_unicode=True)

希望这会有所帮助。

【讨论】:

  • 我在尝试按照您的方式操作时遇到错误:TypeError: 'use_unicode' is an invalid keyword argument for this function
  • 适用于我的 MySQL-python==1.2.5。你用的是哪个版本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多