使用hash格式的put方法,当key已经存在时,则更新该key的键值,若没有该key,则向数据库中插入一条新的记录,demo代码如下:
插入或是更新的代码片段:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using BerkeleyDb;
namespace BerkeleyDBDemo
{
public class Class18
{
static void Main(string[] args)
{
People a=new People()
{
Age=20,
Name="30"
};
Db db = new Db(DbCreateFlags.None);
try
{
DbFile dbf = db.Open(null, @"Tasks.asap", null, DbType.Hash, Db.OpenFlags.Create, 0);
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, a);
DbEntry _key = DbEntry.InOut(Encoding.UTF8.GetBytes("1"));
DbEntry _data = DbEntry.InOut(stream.ToArray());
if (dbf.Put(null, ref _key, ref _data) != 0)
Console.Write("{0}:输入错误", "");
//dbf.Put(null, ref _key, ref _data);
dbf.Sync();//数据更新
}
catch (Exception ex)
{
Console.WriteLine("打开数据库Tasks.p失败");
}
db.Close();
}
}
}
遍历查看结果
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using BerkeleyDb;
namespace BerkeleyDBDemo
{
public class Class19
{
static void Main(string[] args)
{
//遍历数据
using (Db db = new Db(DbCreateFlags.None))
{
//这里如果应用Db.OpenFlags.Create则在启动后会覆盖同名文件,并新建同名文件
//Db.OpenFlags.Truncate会清空数据库
DbHash dbf = (DbHash)db.Open(null, @"Tasks.asap", null, DbType.Hash,
Db.OpenFlags.ThreadSafe, 0);
using (DbHashCursor cursor = dbf.OpenCursor(null, DbFileCursor.CreateFlags.None))
{
foreach (KeyDataPair kdp in cursor)
{
//int k = BitConverter.ToInt32(kdp.Key.Buffer, 0);
//Console.WriteLine("k={0}", k.ToString());
string k = Encoding.UTF8.GetString(kdp.Key.Buffer, 0, kdp.Key.Size);
Console.WriteLine("key={0}", k);
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
stream.Write(kdp.Data.Buffer, 0, kdp.Data.Size);
stream.Seek(0, SeekOrigin.Begin);
People p2 = (People)bf.Deserialize(stream);
Console.WriteLine("Age={0}", p2.Age);
Console.WriteLine("Name={0}", p2.Name);
}
}
}
Console.ReadLine();
}
}
}