Previous Next JavaScript must be enabled to correctly display this content

## Using Binary

You can declare a field as binary using the `BINARY` statement. You then read and write the field value using a Java byte array.

If you want to store a large binary object, then you should use the LOB APIs rather than a binary field.

Note that fixed binary should be used over the binary datatype any time you know that all the field values will be of the same size. Fixed binary is a more compact storage format because it does not need to store the size of the array. See Using Fixed Binary for information on the fixed binary datatype.

To define a simple two-field table where the primary key is a UID and the second field contains a binary field, you use the following statement:

    CREATE TABLE myTable (
        uid INTEGER,
        myByteArray BINARY,
        PRIMARY KEY(uid)
    )

`DEFAULT` and `NOT NULL` constraints are not supported for binary values.

To write the byte array, use `Row.put()`.

    TableAPI tableH = kvstore.getTableAPI();

    Table myTable = tableH.getTable("myTable");

    Row row = myTable.createRow();
    row.put("uid", 12345);

    String aString = "The quick brown fox.";
    try {
        row.put("myByteArray", aString.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace();
    }

    tableH.put(row, null, null);

To read the binary field, use `Row.get().asBinary()`. This returns a `BinaryValue` class instance. You can then use `BinaryValue.get()` to retrieve the stored byte array.

For example:

    TableAPI tableH = kvstore.getTableAPI();

    Table myTable = tableH.getTable("myTable");

    /* Create a primary key for user id 12345 and get a row */
    PrimaryKey key = myTable.createPrimaryKey();
    key.put("uid", 12345);
    Row row = tableH.get(key, null);

    byte[] b = row.get("myByteArray").asBinary().get();
    String aString = new String(b);
    System.out.println("aString: " + aString);