You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取MySQL中binary(16)字段转整数失败问题求助

解决Python读取MySQL binary(16)字段转整数的问题

问题分析

你的fieldA字段是binary(16)类型,存储的是字符串形式的数字(如171099),但因为binary是固定长度类型,系统会在字符串末尾补\x00空字节填充到16位。直接用int()转换时,空字节会被当成无效字符导致报错;而int.from_bytes()是将字节序列当作二进制整数解析,和存储的字符串数字逻辑不符,所以得到错误结果。

解决方案

方案1:在Python中处理字节数据

先去除末尾的空字节,再转换为整数:

query = "SELECT `fieldA` FROM `table` LIMIT 1"
connection = sql.connect(user=user,password=pw,host=host,port=port,database=db)
cursor = connection.cursor()
cursor.execute(query)
df = pd.DataFrame(cursor.fetchall(), columns=['fieldA'])  # 指定列名避免索引问题

# 处理字段值
raw_value = df['fieldA'][0]
# 去除末尾空字节,解码为字符串后转整数
clean_value = raw_value.rstrip(b'\x00').decode('utf-8')
print(int(clean_value))

方案2:在SQL查询时直接转换(更高效)

利用MySQL的CAST函数,查询时直接将binary字段转换为整数,避免Python端额外处理:

# 修改查询语句,直接转换字段类型
query = "SELECT CAST(`fieldA` AS UNSIGNED) AS fieldA FROM `table` LIMIT 1"
connection = sql.connect(user=user,password=pw,host=host,port=port,database=db)
cursor = connection.cursor()
cursor.execute(query)
df = pd.DataFrame(cursor.fetchall(), columns=['fieldA'])

# 直接输出整数
print(df['fieldA'][0])

关键说明

  • rstrip(b'\x00'):针对字节类型的binary值,去除末尾所有空字节;如果是已解码的字符串,用rstrip('\x00')。
  • CAST(fieldA AS UNSIGNED):MySQL会自动忽略binary字段末尾的空字节,将有效数字字符串转换为无符号整数,适合存储数字的binary字段场景。

内容的提问来源于stack exchange,提问作者Mart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:23:10