databases icon indicating copy to clipboard operation
databases copied to clipboard

Convert mysql bit column to Python boolean

Open jhoelzl opened this issue 4 years ago • 0 comments

Hello!

When i select a bit column from a mysql table (with a raw query), the value for 1 looks like b'\x01'.

In mysqlclient package i can adjust the mapping between mysql and Python data types by the conv parameter:

from MySQLdb import converters

def convert_bit_to_bool(bit):
    """
    Convert Mysql bit to Python bool
    When Mysql bit is NULL, then use Python None instead
    :param bit:
    :return: converted_value
    """

    if bit:
        converted_value = bool(ord(bit))
    else:
        converted_value = None

    return converted_value

data_conversation = converters.conversions
data_conversation[MySQLdb.constants.FIELD_TYPE.BIT] = convert_bit_to_bool

connection = MySQLdb.connect(
            host='xxx',
            port=1234,
            user=xxx,
            passwd=xxx,
            db='xxx',
            charset='utf8',
            conv=data_conversation,
        )

How can i achieve this with the databases library? Thanks!

jhoelzl avatar Jun 02 '21 12:06 jhoelzl