バイナリの使用

BINARY文を使用して、フィールドをバイナリとして宣言できます。次に、フィールド値をbase64でエンコードされたバッファとして読み書きします。

すべてのフィールド値が同じサイズであることがわかっている場合、バイナリ・データ型より優先して固定バイナリを使用してください。固定バイナリは、配列のサイズを格納しておく必要がないため、コンパクトなストレージ形式です。固定バイナリ・データ型の詳細は、固定バイナリの使用を参照してください。

主キーがUIDで2番目のフィールドがバイナリ・フィールドを持つシンプルな2つのフィールドの表を定義するには、次の文を使用します。

CREATE TABLE myTable (
    uid INTEGER,
    myByteArray BINARY,
    PRIMARY KEY(uid)
) 

バイナリ値では、DEFAULTおよびNOT NULL制約はサポートされていません。

バイナリ・フィールドを記述するには、データをストアに書き込む前に、Store.encode_base_64()メソッドを使用してエンコードします。

    iFile = open("image.jpg")
    image = store.encode_base_64(iFile.read())
    iFile.close()
     
    row_d = {'uid' : 0,
             'myByteArray' : image
            }
    try:
        store.put("myTable", row_d)
        logging.debug("Store write succeeded.")
    except IllegalArgumentException, iae:
        logging.error("Could not write table.")
        logging.error(iae.message)
        sys.exit(-1) 

バイナリ・フィールドを読み取るには、任意のデータ・フィールドと同様に取得します。データをディスクに書き込む前に、Store.decode_base_64()を使用してデコードします。

次に例を示します。

    try:
        primary_key_d = {"uid" : 0}
        row = store.get("myTable", primary_key_d)
        if not row:
            logging.debug("Row retrieval failed")
        else:
            logging.debug("Row retrieval succeeded.")
            image = store.decode_base_64(row['myByteArray'])
            iFile = open("out.jpg", 'w')
            iFile.write(image)
            iFile.close()
    except IllegalArgumentException, iae:
        logging.error("Row retrieval failed.")
        logging.error(iae.message)
        return
    except KeyError, ke:
        logging.error("Row display failed. Bad key: %s" % ke.message)