issue is this: in (pl)python code, we've calculated an integer = 26663. Can easily convert this to hex using hex(myint) = 0x6827
So far so good!
Now, how to write this value -into a concatenation of strings- into a PostgreSQL (v9) bytea field? The DB is UTF8-encoded, if this matters.
EG, neither of these examples will work:
Here, of course, I cannot concatenate 'str' and 'int' objects:
rv = plpy.execute(plan, [ (string1 + 6827) ])
This one inputs the wrong hex code for 0x6开发者_高级运维827
rv = plpy.execute(plan, [ (string1 + str('6827')) ])
Help!
I'm not familiar with Postgres, but the hex(n)
function returns a string representation of the numeric value of n
in hexadecimal. The nicest way in my opinion to concatenate this with a string is to use format strings. For example:
rv = plpy.execute(plan, [ ( 'foo %s bar' % hex(6827) ) ] )
If the string is really in a variable called string1
, and you only need to append it with the hex value, then simple concatenation using the + sign will work fine:
rv = plpy.execute(plan, [ ( string1 + hex(6827) ) ])
This works without conversion because the hex() function returns a string.
If you don't actually want to store a printable string representation, but rather a binary string, use the struct module to create an array of bytes.
import struct
bytes = struct.pack('i', 6827) # Ignoring endianness
A lot of people are confused about what storing something as "binary" actually means, and since you are using a field type (bytea
) which seems to be intended for binary storage, maybe this is what you actually want?
The returned value from bytes will be a string that you can either concatenate with another string, or continue to pack more binary values into.
See the struct module documentation for more information!
精彩评论