2011-12-19 112 views
1

从Android SQLite数据库的角度来看 - 我有一个表有一个BLOB类型的字段,然后我想根据这个BLOB字段来查询这个表内容。SQLite查询与字节[] WHERE子句

我可以用ContentValues插入我的BLOB字段,并使用检索:

cursor.getBlob(0)// index 

我只是无法弄清楚如何查询在此基础上BLOB字段此表中的内容,并没有发现任何有关此问题。

回答

2

您无法查询blob的(text?binary?other?)内容。

如果你看看,你会看到的内容是十六进制:

实例:X'53514C697465' 。

意见建议:

创建一个新的文本列,例如: “blob_index”。您可以在“索引”列上搜索,然后获取blob。

另外,只需将数据存储为“文本”即可。

0

我发现你可以在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); 
}