Search code examples
mysqljdbcprepared-statementhex

JDBC PreparedStatement with Hexadecimal Literals


I have a Mysql compatible Hexadecimal Literal, for example X'4D7953514C' How do I assign such a value with PreparedStatments, I tried setString but the value gets wrapped into quotes.

The goal is to have a sql statement that looks like this (col1 is a varchar):

insert into t1 (col1) values (x'4D7953514C'); 

Solution

  • You can't set hexadecimal strings like x'4D7953514C' directly using JDBC. You either need to use setString() with the actual intended value (MySQL), or use setBytes() with a byte array with the right values (eg new byte[] {0x4D, 0x79, 0x53, 0x51, 0x4C }, although I am not 100% sure this works with MySQL Connector/J).

    The X'...' is the SQL syntax for binary literals. When you are using parametrized queries you aren't using literals, you are using parameters, so the literal syntax does not apply.