java - How to use SQLite UNIQUEIDENTIFIER type fields in Java
问题描述
I have a Sqlite database with Id fields declared as type UNIQUEIDENTIFIER. The DB Browser for SQLite shows these fields as type BLOB and the type of data in cell as Binary 16 bytes. They looks like "a1 75 e0 47 e6 07 47 37 a7 ea 0a 8d 7f 22 f6 55". My question is how to store these type of field from a resultset to use them in another SQL statement. Example:
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;
I had tried with id as type byte, array of bytes, inputstream, nothing works. Thanks for your answer.
解决方案
They probably implemented 16 unique bytes by a UUID. Unfortunately there is no appropriate SQL type in ResultSet access. The java class UUID is a fitting data holder:
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));
The reasons for not using byte[]
is: it is a too low level type, not saying anything and in need of some operations.
UUID on the other hand bears the meaning of a unique identifier. It als has equals
, compareTo
, hashCode
and even a somewhat readable toString
.
推荐阅读
- python - 使用 Python 处理查询中的 BigQuery 错误
- javascript - 如何刮掉面包屑内部文本并将其用作我的 Google 标记管理器中的变量
- artificial-intelligence - 哪些个体应该在遗传算法中交叉和/或变异?
- php - 未定义的变量,即使它已定义 Laravel
- function - Lua:返回没有相邻重复的彩虹文本
- java - 在 Scala 中初始化 Apache Beam 测试管道失败
- swift - 如何在特殊字符后获取字符串中的值
- c# - 如何安全地附加到 ProcessStartInfo.EnvironmentVariables["PATH"]
- c# - 部分类的多重继承
- python - 我应该返回一个通过引用传递并修改的列表吗?