databases
databases copied to clipboard
Convert mysql bit column to Python boolean
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!