How do I convert STRING to VARBINARY in java?

ERP picture ERP · Feb 9, 2016 · Viewed 7.8k times · Source

I have a String containing XML tags that I want to convert to VARBINARY and post it to stored procedure in SQL Server.

I don't know how to convert a String to VARBINARY. Please advise!

Answer

Henrik Gustafsson picture Henrik Gustafsson · Feb 9, 2016

If you have a PreparedStatement you should be able to do something like this:

// This is your input string
String value = "SomeValue";

// Your query goes here
PreparedStatement s = connection.prepareStatement(
    "UPDATE TheTable SET XmlField = ? WHERE Id = ?");

// Convert the input string to bytes according to the UTF-8 character encoding
byte[] varBinary = value.getBytes(StandardCharsets.UTF_8);

// Set the XmlField parameter in the prepared statement.
s.setBytes(1, varBinary)

// ID field
s.setInt(2, 42)