Question

In my Sybase 12.0 ASE database, I have at table that contains a column defined as binary(16) and used to store GUIDS/UUIDs. When i run a select query using a SQL client + ansi SQL for that table, all looks fine..i can see the guid value as i expect it in the resultset (the guid looks something like this "1ae5608d12311de123d001185135a13" in the sql output)

However in code when trying to do this via JDBC(I am using the Sybase "com.sybase.jdbc3.jdbc.SybDriver" driver), when i iterate over the result set and try to read that columnn, it comes back as basically garbage. if i do a ResultSet.getObject(col), where col is the binary column index in my resultset, i see that the type is byte[]. I have tried converting this to string and encoding as Base64, but to no avail.

Any ideas on how to do this?

Thanks

Was it helpful?

Solution

The byte[] you receive is exactly what it should be: A sequence of 16 bytes or less, according to the column definition.

What representation of the UID are you trying to create? - They're not usually represented as Base64 but rather as Hex.

Trying to convert the byte[] to a String directly is certainly not what you want.
If you iterate over the array, converting each byte to its (2-digit!) hexadecimal representation (String), and concat those strings to a string of length 32, the result will probably look a lot more like what you need.

If you want to use java.util.UUID, you should build two long values from the first and the second set of eight bytes, respectively, to be passed to the constructor.

Edit:

In java.util.UUID you can find:

/*
 * Private constructor which uses a byte array to construct the new UUID.
 */
private UUID(byte[] data) {
    long msb = 0;
    long lsb = 0;
    assert data.length == 16;
    for (int i=0; i<8; i++)
        msb = (msb << 8) | (data[i] & 0xff);
    for (int i=8; i<16; i++)
        lsb = (lsb << 8) | (data[i] & 0xff);
    this.mostSigBits = msb;
    this.leastSigBits = lsb;
}

I have no idea why it is not public...

Given your byte[] you can create the two long values needed for the UUID(long,long constructor with exactly this code.

You will only have to pay attention to the ordering of the bytes in the array you receive from the DB; which one is the least significant byte, which is the most significant byte. (Probably either [0] and [15], or [15] and [0].)

Once you have an instance of UUID you can use its toString() to get the common representation.

If you don't want to use UUID you'd have to convert bytes to hex yourself for output and maybe insert some dashes for readability.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top