如何在 Java 中使用 SQLite UNIQUEIDENTIFIER 类型字段

How to use SQLite UNIQUEIDENTIFIER type fields in Java

我有一个 Sqlite 数据库,其 Id 字段声明为 UNIQUEIDENTIFIER 类型。 SQLite 的数据库浏览器将这些字段显示为 BLOB 类型,单元格中的数据类型显示为二进制 16 字节。他们看起来像 "a1 75 e0 47 e6 07 47 37 a7 ea 0a 8d 7f 22 f6 55"。 我的问题是如何从结果集中存储这些类型的字段以在另一个 SQL 语句中使用它们。示例:

      sql = "select id from contract where customer= 'John'"
      ps = connection.prepareStatement(sql);
      rs = ps.executeQuery();
      while (rs.next() {
          id = rs.getString(1);
      }
      sql = "select * from invoices where customerid = " + id;

我曾尝试将 id 作为字节类型、字节数组、输入流,但没有任何效果。谢谢你的回答。

他们可能通过 UUID 实现了 16 个唯一字节。不幸的是,在 ResultSet 访问中没有合适的 SQL 类型。 java class UUID 是合适的数据持有者:

public static UUID toUUID(byte[] bytes) {
    ByteBuffer idBuffer = ByteBuffer.wrap(bytes);
    return new UUID(idBuffer.getLong(), idBuffer.getLong());
}

    UUID uuid = toUUID(rs.getBytes(1));

public static byte[] fromUUID(UUID uuid) {
    byte[] bytes = new byte[16];
    ByteBuffer idBuffer = ByteBuffer.wrap(bytes);
    idBuffer.putLong(uuid.getMostSignificantBits());
    idBuffer.putLong(uuid.getLeastSignificantBits());
    return bytes;
}

    rs.setBytes(1, fromUUID(uuid));

使用byte[]的原因是:类型太低,没啥好说的,需要一些操作

UUID则具有唯一标识的意思。它也有 equalscompareTohashCode 甚至有点可读性 toString.