Imran Azad
Imran Azad

Reputation: 55

Save byte string to varchar column in database

Below is the contents of a tuple:

('g\xba\xfc\x995m\x9a\xf0\x1d\x8b4f1\x05\xdel\xc8;\x10\xffl\xfd{\xc7MA!\x90\xe5N
\xf9\x98\xf80\xe0wu\x82B\xb5\xc6\xb1T\\Px_\xfarT\x04\xd4\xe1\xfb?\x81\xa2M\x94P\
xa6\x89bM\x00\x18Q\xf7\x979\xd4V\xc5=\xc6\xff.\xf4\x857\t\xdd\xb0\xe4\xda\x1b8\x
b6T\xfbK\x0c\xd4\xc8\x99\xd0\r\xfd\x18\xcfd\x15C\xfaF)\xacuAU\xeb\xb2\xa6\xd9\xb
5-\xa6[\xad6\x17\x13\xe5\xeeqnR"7\xbc\x93\x99\x07H\xbe\nG\x9ejR\xe8\xb5\xdc\xb7\
x93\xc5\x15\'\x95\xb7k\x89\x9d\x04G\xfe\x11\xfa\x0f\x18u\x90v,[\x80_\x93\x0f\xec
\x8cX0\xc7e\xd4\x10\xb7\x89\xe23y\xebo\x06\x11/\x01\x17\xc5U\x87\xbd\xfc\xa6\xbd
\x05\xcb\x9fOWNP\xe8zB`"\x9b\xbf\x0c\xaa\x9b\xfe\x95\x0f\xf5\x81f\x04\xa4c\xae\x
f8\x11\xd6\xcaL\xcf\xd2ZCJ\xcc\x94e\xc3Q_\x8c\xa7\x12\xe3F\xdc\x08*\x98f\xac\x99
\xdf\x0ey\x1dy',)

It is a byte string which I would like to convert to a string and insert into the database(mysql) and then also convert back to a byte string.

Thanks

Upvotes: 4

Views: 3365

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500135

If it's an arbitrary byte string, you should use something like base64 to convert it to text:

import base64
encoded = base64.b64encode(byteString)
# Now insert "encoded" into the database

Then:

import base64
# Retrieve encoded from the database...
byteString = base64.b64decode(encoded)

You should not just try to treat it as encoded text unless it really is encoded text.

Alternatively, if you're in control of the database schema, you should consider changing the table to use a binary-oriented column instead of a text-oriented one.

Upvotes: 7

Related Questions