【问题标题】:Python MySQL connector returns bytearray instead of regular string valuePython MySQL 连接器返回字节数组而不是常规字符串值
【发布时间】:2017-04-16 17:20:47
【问题描述】:

我正在将一个表中的数据加载到 pandas 中,然后将该数据插入到新表中。但是,我看到的不是普通的字符串值,而是 bytearray。

bytearray(b'TM16B0I8') 应该是TM16B0I8

我在这里做错了什么?

我的代码:

engine_str = 'mysql+mysqlconnector://user:pass@localhost/db'
engine = sqlalchemy.create_engine(engine_str, echo=False, encoding='utf-8')
connection = engine.connect()

th_df = pd.read_sql('select ticket_id, history_date', con=connection)

for row in th_df.to_dict(orient="records"):
    var_ticket_id = row['ticket_id']
    var_history_date = row['history_date']

    query = 'INSERT INTO new_table(ticket_id, history_date)....'

【问题讨论】:

  • 你在哪里看到字节数组?与上述代码相关的任何地方?
  • 所以当我打印th_df['ticket_id'] 时,不是给我一个字符串'TM16A0JY',而是给我这个数组[77, 83, 90, 45, 48, 50, 53, 52, 57, 56],当我查看数据库时插入之后它显示@987654327 @。有趣的是,对于整数 ID,它没有显示 bytearray,也没有在 db 中插入一个整数值。 4567.

标签: python mysql python-3.x pandas sqlalchemy


【解决方案1】:

由于某种原因,Python MySql 连接器仅返回 bytearrys,(更多信息在 (How return str from mysql using mysql.connector?) 但您可以将它们解码为 un​​icode 字符串

var_ticket_id = row['ticket_id'].decode()
var_history_date = row['history_date'].decode()

【讨论】:

    【解决方案2】:

    确保您使用了正确的排序规则和编码。我碰巧将UTF8MB4_BIN 用于我的一个网站数据库表。把它改成utf8mb4_general_ci,就成功了。

    【讨论】:

    • 这太完美了——我也有类似的问题,通过将排序规则从 latin1_bin 更改为 COLLATE latin1_general_ci 来解决。谢谢@Yongju Lee
    【解决方案3】:

    生成 bytearray 现在是预期的行为。

    随着 mysql-connector-python 8.0.24 (2021-04-20) 发生变化。根据v8.0.24 release notes,“二进制列作为字符串返回,而不是 'bytes' 或 'bytearray'”行为是该版本中修复的错误。

    因此,如果数据库列是二进制类型(例如 binaryvarbinary),则生成 Python binaryarray 是正确的行为。以前,它产生一个 Python string,但现在它产生一个 binaryarray

    因此,要么将数据库中的数据类型更改为非二进制数据类型,要么在代码中将 binaryarray 转换为 string。如果该列可以为空,则必须先检查该列;因为尝试在None 上调用decode() 方法会产生错误。您还必须确保字节代表一个有效的字符串,在用于解码/转换的字符编码中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 2015-05-24
      • 1970-01-01
      相关资源
      最近更新 更多