zoukankan      html  css  js  c++  java
  • Berkeley DB .net 进行添加和更新操作

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

  • 相关阅读:
    POJ 1837 Balance 水题, DP 难度:0
    POJ 3126 Prime Path bfs, 水题 难度:0
    python学习笔记day01 练习题
    python学习笔记day01_08 循环语句while
    python学习笔记day01_07 流程控制语句
    python学习笔记day01_06 基础数据类型
    python学习笔记day01_05 运行py程序--常量,变量,注释
    python学习笔记day01_04 python分类
    python学习笔记-day01_02计算机基础
    PAT 甲级 1134 Vertex Cover
  • 原文地址:https://www.cnblogs.com/lexus/p/1260065.html
Copyright © 2011-2022 走看看