另外Berkeley DB數據庫的操作需要借助於序列化。
/// <summary>
/// 二進制序列化
/// </summary>
private BinaryFormatter formatter;
/// <summary>
/// 鍵內存流
/// </summary>
private MemoryStream keyStream;
/// <summary>
/// 內容內存流
/// </summary>
private MemoryStream dataStream;
private void StreamInit()
{
formatter = new BinaryFormatter();
keyStream = new MemoryStream();
dataStream = new MemoryStream();
}
Berkeley DB是鍵值數據庫,因此定義一個獲取鍵接口:
public interface IPut
{
string Key { get; }
}
一、數據庫的保存與更新
public bool Set(IPut put)
{
Reset();
keyStream.Position = 0;
formatter.Serialize(keyStream, put.Key);
DbEntry key = DbEntry.InOut(keyStream.GetBuffer(), 0, (int)keyStream.Position);
dataStream.Position = 0;
formatter.Serialize(dataStream, put);
DbEntry data = DbEntry.InOut(dataStream.GetBuffer(), 0, (int)dataStream.Position);
WriteStatus status = btree.Put(txn, ref key, ref data);
switch (status)
{
case WriteStatus.Success:
return true;
case WriteStatus.NotFound:
case WriteStatus.KeyExist:
default:
return false;
}
}
上述代碼就可以保存鍵值。顯示對鍵值進行序列化,然後再保存。保存完有三個狀態,可以一一處理。