Skip to main content
 首页 » 编程设计

C# Berkeley DB .net 进行添加和更新操作

2022年07月19日150三少

使用hash格式的put方法,当key已经存在时,则更新该key的键值,若没有该key,则向数据库中插入一条新的记录,demo代码如下:

插入或是更新的代码片段:

Code

遍历查看结果

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();
        }
    }
}


本文参考链接:https://www.cnblogs.com/lexus/archive/2008/08/04/1260065.html