Insert hex values into MySql

后端 未结 4 1628
一个人的身影
一个人的身影 2020-12-05 10:20

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 t

相关标签:
4条回答
  • 2020-12-05 10:47

    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.

    0 讨论(0)
  • 2020-12-05 10:50

    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
    
    0 讨论(0)
  • 2020-12-05 10:54

    Or you can do even this:

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

    See this for some more info.

    0 讨论(0)
  • 2020-12-05 10:55

    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.

    http://www.xaprb.com/blog/2009/02/12/5-ways-to-make-hexadecimal-identifiers-perform-better-on-mysql/

    0 讨论(0)
提交回复
热议问题