Tim
Tim

Reputation: 397

Insert hex values into MySql

I have a table with a VARBINARY column. I need to insert a string such as '4D2AFF' which represents the hex values 0x4D, 0x2A and 0xFF respectively. How do I construct this statement?

Upvotes: 30

Views: 42479

Answers (4)

Riedsio
Riedsio

Reputation: 9926

Here's a great blog post I always refer to to remind myself of the proper handling of hex values and binary fields, and lays out some performance implications.

https://planet.mysql.com/entry/?id=17498

Upvotes: 2

nawfal
nawfal

Reputation: 73173

Or you can do even this:

INSERT INTO tbl (col) VALUES (X'4D2AFF')

See this for some more info.

Upvotes: 12

aronchick
aronchick

Reputation: 7128

The Hex() and Unhex() functions were already mentioned, but I'd like to weigh in as well on an alternative pattern.

How are you using the strings before and after? If you can avoid coversion until the last possible minute, that is highly preferential. That way you don't risk something going wrong, or forgetting whether or not the object you've extracted from the DB has already been converted or not.

Upvotes: 3

BalusC
BalusC

Reputation: 1108722

You can use UNHEX() function to convert a hexstring with hex pairs to binary and HEX() to do the other way round.

I.e.

INSERT INTO tbl (col) VALUES (UNHEX('4D2AFF'))

and

SELECT HEX(col) FROM tbl

Upvotes: 42

Related Questions