[英]SQLite query with byte[] WHERE clause
從Android SQLite數據庫的角度來看 - 我有一個表有一個BLOB類型的字段然后我想根據這個BLOB字段查詢這個表內容。
我可以使用ContentValues
插入我的BLOB字段並使用以下命令檢索它:
cursor.getBlob(0)// index
我只是無法弄清楚如何根據此BLOB字段來查詢此表的內容,卻未發現有關此問題的任何信息。
您無法查詢Blob的(文本?二進制?其他?)內容。
如果你看,你會看到內容是十六進制的:
實施例:X'53514C697465'。
建議:
創建一個新的文本列,例如“ blob_index”。 您可以在“索引”列上進行搜索,然后獲取Blob。
或者,只需將數據存儲為“文本”。
我發現你可以查詢一個blob。 需要在查詢中使用hex()函數。
例如,我在我的數據庫行中使用UUID作為我可以在本地生成的唯一鍵,並且仍然確保服務器上的唯一性。
CREATE TABLE example (_ID INTEGER PRIMARY KEY AUTOINCREMENT, uuid BLOB NON NULL UNIQUE, ...)
插入數據時,以下工作:
final ContentValues values = new ContentValues(4); values.put(Contract.Line.COL_UUID, UuidFactory.toBlob(uuid));
給定表單中的查詢URI:
content://package.example.com/example/uuid/11112222-3333-0444-0555-666677778888
查詢變為:
final SQLiteDatabase db = mHelper.getReadableDatabase(); return db.query(table, projection, "hex(uuid) = ?", new String[] { UuidFactory.toHex(uri.getLastPathSegment()) }, null, null, null, null);
在UuidFactory
(它還包含生成新UUID的代碼)中,定義了以下靜態函數:
@NonNull public static String toHex(@NonNull final UUID uuid) { return String.format("%016X%016X", uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()); } @NonNull public static String toHex(@NonNull final String uuid) { return toHex(UUID.fromString(uuid)); } @NonNull public static byte[] toBlob(@NonNull final UUID uuid) { final ByteBuffer buf = ByteBuffer.allocate(16); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); return buf.array(); }
為了完整性:
@NonNull public static UUID fromBlob(@NonNull final byte[] array) { final ByteBuffer buf = ByteBuffer.allocate(16); buf.mark(); buf.put(array); buf.reset(); final long msb = buf.getLong(); final long lsb = buf.getLong(); return new UUID(msb, lsb); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.