0

I am trying to insert byte array into Blob data type in my Cassandra table.. I am using Datastax Java driver. Below is my code -

for (Map.Entry<String, byte[]> entry : attributes.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

    String cql = "insert into test_data (user_id, name, value) values ('"+userId+"', '"+entry.getKey()+"', '"+entry.getValue()+"');";

    System.out.println(cql);

    CassandraDatastaxConnection.getInstance();

    CassandraDatastaxConnection.getSession().execute(cql);

}

And this is the exception I am getting back -

InvalidQueryException: cannot parse '[B@50908fa9' as hex bytes

I guess the problem is, the way I am making my above cql.. Something is missing for sure...

I have created the table like this -

create table test_data (user_id text, name text, value blob, primary key (user_id, name));

Can anybody help me? Thanks...

AKIWEB
  • 19,008
  • 67
  • 180
  • 294

1 Answers1

1

The problem is that when you append the byte array to the String it calls toString on the byte[] which prints the unhelpful pointer you are seeing. You need to manually convert it to a String for your data type. In your case you are using a blob, so you need to convert to a hex string.

This question has code for converting the byte[] to String:

How to convert a byte array to a hex string in Java?

You can use one of those functions and prepend '0x' to it. Then you should have a valid String for your blob.

Community
  • 1
  • 1
Richard
  • 11,050
  • 2
  • 46
  • 33
  • Am I appending byte array to String in my code? If yes, can you point me where I am doing it? Is there any way, I can directly store byte array in the blob? As I was expecting that we an store byte array in blob data type in Cassandra? or storing byte array as string is also the same thing? – AKIWEB Oct 15 '13 at 07:06
  • Here: `String cql = "insert into test_data (user_id, name, value) values ('"+userId+"', '"+entry.getKey()+"', '"+entry.getValue()+"');";` entry.getValue() returns a byte[]. A blob stores arbitrary binary data but it must be encoded as a hex string to insert with CQL. – Richard Oct 15 '13 at 07:33