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

问题描述 投票:0回答:1

我有一个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作为字节类型,字节数组,inputstream,没有任何作用。感谢您的回答。

java sqlite uniqueidentifier
1个回答
0
投票

他们可能通过UUID实现16个唯一字节。不幸的是,ResultSet访问中没有适当的SQL类型。 Java类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
© www.soinside.com 2019 - 2024. All rights reserved.