【问题标题】:pymysql returns wrong values for BIT typepymysql 为 BIT 类型返回错误的值
【发布时间】:2021-01-03 03:03:56
【问题描述】:

我正在使用pymysql==0.10.1 (python3.7) 读取具有 BIT 列的表,并得到错误的值:

CREATE TABLE root.numeric
(BIT_COL       BIT(10));
insert into root.numeric
values (b'0010001000');
insert into root.numeric
values (b'0000100000');

然后

        with connection.cursor() as cursor:
                sql = f"select * from `root`.`numeric`;"
                cursor.execute(sql)
                result = cursor.fetchone()
                print("mysql payload", result)

得到:

mysql payload {'BIT_COL': b'\x00\x88'} # nice
mysql payload {'BIT_COL': b'\x00 '}.   # not nice

这是为什么呢?我检查了一下,看起来 pymysql 代码没有为 BIT 字段转换任何内容。

【问题讨论】:

    标签: python mysql type-conversion pymysql


    【解决方案1】:

    正如code 中提到的“MySQLdb 不处理位,所以我们也不应该”,所以正确的转换是:

        def convert_bit(self, b):
            """ bit fields are packed as big-endian unsigned long long,
                we translate them to human-readable int/long"""
            b = b"\x00" * (8 - len(b)) + b # pad w/ zeroes
            return struct.unpack(">Q", b)[0]
    

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2021-04-15
      • 2021-01-25
      相关资源
      最近更新 更多