【问题标题】:How to use SQLite UNIQUEIDENTIFIER type fields in Java如何在 Java 中使用 SQLite UNIQUEIDENTIFIER 类型字段
【发布时间】:2020-01-15 09:20:42
【问题描述】:

我有一个 Sqlite 数据库,其中 Id 字段声明为 UNIQUEIDENTIFIER 类型。 SQLite 的 DB 浏览器将这些字段显示为 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,

标签: java sqlite uniqueidentifier


【解决方案1】:

他们可能通过 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

【讨论】:

  • Joop 提供的解决方案是正确的,它就像一个魅力!谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
相关资源
最近更新 更多