db4o学习笔记(二)、第一次亲密接触

本文介绍了db4o数据库的基本操作,包括存储、更新、加载和删除简单对象实例的过程。通过实例展示了如何使用db4o进行数据操作。

  让我们以一个简单的例子作为db4o之旅的开始,通过这个例子展示如何存储、更新、加载以及删除一个只包括系统内置类型及字符串成员的简单对象实例,这个对象是一个存储了F1车手(Pilot)的相关信息如姓名及本赛季所取得积分的类。

  首先我们将创建一个类来存储这些信息,它看上去像这样:

 1 None.gif namespace  com.db4o.f1.chapter1
 2 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 3InBlock.gif    public class Pilot
 4ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 5InBlock.gif        string _name;
 6InBlock.gif        int _points;
 7InBlock.gif        
 8InBlock.gif        public Pilot(string name, int points)
 9ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
10InBlock.gif            _name = name;
11InBlock.gif            _points = points;
12ExpandedSubBlockEnd.gif        }

13InBlock.gif        
14InBlock.gif        public string Name
15ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
16InBlock.gif            get
17ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
18InBlock.gif                return _name;
19ExpandedSubBlockEnd.gif            }

20ExpandedSubBlockEnd.gif        }

21InBlock.gif        
22InBlock.gif        public int Points
23ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
24InBlock.gif            get
25ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
26InBlock.gif                return _points;
27ExpandedSubBlockEnd.gif            }

28ExpandedSubBlockEnd.gif        }
   
29InBlock.gif        
30InBlock.gif        public void AddPoints(int points)
31ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
32InBlock.gif            _points += points;
33ExpandedSubBlockEnd.gif        }
    
34InBlock.gif        
35InBlock.gif        override public string ToString()
36ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
37InBlock.gif            return string.Format("{0}/{1}", _name, _points);
38ExpandedSubBlockEnd.gif        }

39ExpandedSubBlockEnd.gif    }

40ExpandedBlockEnd.gif}

41 None.gif

  请注意:在类定义的代码中没有包含任何db4o相关的代码。

  2.1、打开数据库

  为打开已有的或新建一个db4o数据库我们使用Db4o.OpenFile()函数,并为其传入一个特定路径的文件名作为参数,以此来获得特定的ObjectContainer实例。ObjectContainer对外就是一个数据库,也是我们操作db4o的主要接口。关闭ObjectContainer使用#.Close()函数,它将会关闭数据库文件并释放其占用的系统资源。

 1 None.gif [accessDb4o]
 2 None.gifObjectContainer db = Db4o.OpenFile(Util.YapFileName);
 3 None.gif try
 4 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 5InBlock.gif    // do something with db4o
 6ExpandedBlockEnd.gif}

 7 None.gif finally
 8 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 9InBlock.gif    db.Close();
10ExpandedBlockEnd.gif}

  在接下来的例子中假设我们的环境有一个变量"db"来引用和存储数据库文件Util.YapFileName,并会在需要的时候自动的打开或关闭数据库。

  2.2、保存对象

  为了保存对象我们只需要在数据库对象上简单的调用Set()方法并传入适当的参数即可。

1 None.gif [storeFirstPilot]
2 None.gifPilot pilot1  =   new  Pilot( " Michael Schumacher " 100 );
3 None.gifdb.Set(pilot1);
4 None.gifConsole.WriteLine( " Stored {0} " , pilot1);

  好,我们再存入第二个车手对象。
1 None.gif [storeSecondPilot]
2 None.gifPilot pilot2  =   new  Pilot( " Rubens Barrichello " 99 );
3 None.gifdb.Set(pilot2);
4 None.gifConsole.WriteLine( " Stored {0} " , pilot2);

  2.3、加载对象

  db4o提供了三种不同的查询数据的方法,(1)、通过实例查询(QBE);(2)、db4o原生/本地化查询(NQ);(3)、SODA查询接口(SODA是一种通过数据库持久层进行的查询,查询语句被定义在字符串中,并通过持久引擎进行解释执行)。在这一节的例子中我将仅介绍QBE,而在日常的开发中你将对象存储在数据库中后,我们推荐使用db4o主要的查询接口NQ进行查询。

  当使用QBE进行查询时,我们需要为希望加载的数据而创建一个对象原型(prototypical ),db4o将会加载所有与原型相同类型(各成员字段不为默认值)的对象,返回的结果将会存储在ObjectSet对象实例中,我们使用一个"listResult"的函数来显示返回结果。

1 None.gif public   static   void  ListResult(ObjectSet result)
2 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
3InBlock.gif    Console.WriteLine(result.Count);
4InBlock.gif    foreach (object item in result)
5ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
6InBlock.gif        Console.WriteLine(item);
7ExpandedSubBlockEnd.gif    }

8ExpandedBlockEnd.gif}

  为了从数据库中加载所有的车手对象,我们提供了一个初始值为空的Polit原型对象。

1 None.gif [retrieveAllPilotQBE]
2 None.gifPilot proto  =   new  Pilot( null 0 );
3 None.gifObjectSet result  =  db.Get(proto);
4 None.gifListResult(result);

  请注意在提供的原型对象中车手的积分为0,而实际返回的车手对象中则没有包含积分为0的对象,这是因为对于int型字段的默认值为0。

  db4o也提供了一种便捷的方法来加载这些对象:

1 None.gif [retrieveAllPilots]
2 None.gifObjectSet result  =  db.Get( typeof (Pilot));
3 None.gifListResult(result);

  在.NET 2.0中则可以通过泛型来处理:

None.gif IList  < Pilot >  pilots  =  db.query < Pilot > ( typeof (Pilot));

  以下示例则是通过车手的名字或特定的积分来加载车手对象:

 1 None.gif [retrievePilotByName]
 2 None.gifPilot proto  =   new  Pilot( " Michael Schumacher " 0 );
 3 None.gifObjectSet result  =  db.Get(proto);
 4 None.gifListResult(result);  
 5 None.gif
 6 None.gif //  And to query for Pilots with a specific number of points:
 7 None.gif
 8 None.gif[retrievePilotByExactPoints]
 9 None.gifPilot proto  =   new  Pilot( null 100 );
10 None.gifObjectSet result  =  db.Get(proto);
11 None.gifListResult(result); 
12 None.gif

  在db4o中还有其它的一些查询方法,这将在以后的章节中深入的介绍。

  2.4、更新对象

  更新对象跟存储它们一样简单,实际上我们只需要在修改对象后再次调用同样的方法Set()就可以了。

1 None.gif [updatePilot]
2 None.gifObjectSet result  =  db.Get( new  Pilot( " Michael Schumacher " 0 ));
3 None.gifPilot found  =  (Pilot)result.Next();
4 None.giffound.AddPoints( 11 );
5 None.gifdb.Set(found);
6 None.gifConsole.WriteLine( " Added 11 points for {0} " , found);
7 None.gifRetrieveAllPilots(db);

  请注意,在调用Set()方法更新对象之前我们先进行了查询,这一点十分重要。如果在当前的存储或加载操作过程所处的会话中对象对于db4o不可知的话,db4o将会向数据库中插入一个的对象,之所以会这样是因为db4o不会自动的去匹配先前存储于数据库的对象,而是假设你向数据库中存入第二拥有相同属性的对象。   

  为了验证数据库是否确实更新的车手信息,可以执行上面加载数据库对象的方法。

  2.5、更新对象

  删除数据库中的对象使用Delete()方法: 

1 None.gif [deleteFirstPilotByName]
2 None.gifObjectSet result  =  db.Get( new  Pilot( " Michael Schumacher " 0 ));
3 None.gifPilot found  =  (Pilot)result.Next();
4 None.gifdb.Delete(found);
5 None.gifConsole.WriteLine( " Deleted {0} " , found);
6 None.gifRetrieveAllPilots(db);

  可以使用上面提供的加载对象的方法来验证其是否已经从数据库中真正的删除了。

  在更新对象时,对象也将首先被db4o删除,这时提供一个原型对象将不足于进行相关的操作而必须提供一个完全匹配的对象给数据库。

  2.6、小结

  是不是很简单呢?只需要简单的几行代码就完成了对db4o数据库对象的保存、更新、加载及删除操作。而对于复杂的查询任务如何完成呢?我们将通过在下一章中介绍的含有约束条件的QBE查询完成。 
  以下是本单元的所有源代码:

ContractedBlock.gif ExpandedBlockStart.gif 完整的代码
  1None.gifusing System;
  2None.gifusing System.IO;
  3None.gifusing com.db4o;
  4None.gifusing com.db4o.f1;
  5None.gifnamespace com.db4o.f1.chapter1
  6ExpandedBlockStart.gifContractedBlock.gifdot.gif{
  7InBlock.gif    public class FirstStepsExample : Util
  8ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{    
  9InBlock.gif        public static void Main(string[] args)
 10ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 11InBlock.gif            File.Delete(Util.YapFileName);
 12InBlock.gif            AccessDb4o();
 13InBlock.gif            File.Delete(Util.YapFileName);
 14InBlock.gif            ObjectContainer db = Db4o.OpenFile(Util.YapFileName);
 15InBlock.gif            try
 16ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 17InBlock.gif                StoreFirstPilot(db);
 18InBlock.gif                StoreSecondPilot(db);
 19InBlock.gif                RetrieveAllPilots(db);
 20InBlock.gif                RetrievePilotByName(db);
 21InBlock.gif                RetrievePilotByExactPoints(db);
 22InBlock.gif                UpdatePilot(db);
 23InBlock.gif                DeleteFirstPilotByName(db);
 24InBlock.gif                DeleteSecondPilotByName(db);
 25ExpandedSubBlockEnd.gif            }

 26InBlock.gif            finally
 27ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 28InBlock.gif                db.Close();
 29ExpandedSubBlockEnd.gif            }

 30ExpandedSubBlockEnd.gif        }

 31InBlock.gif        
 32InBlock.gif        public static void AccessDb4o()
 33ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 34InBlock.gif            ObjectContainer db=Db4o.OpenFile(Util.YapFileName);
 35InBlock.gif            try
 36ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 37InBlock.gif                // do something with db4o
 38ExpandedSubBlockEnd.gif            }

 39InBlock.gif            finally
 40ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 41InBlock.gif                db.Close();
 42ExpandedSubBlockEnd.gif            }

 43ExpandedSubBlockEnd.gif        }

 44InBlock.gif        
 45InBlock.gif        public static void StoreFirstPilot(ObjectContainer db)
 46ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 47InBlock.gif            Pilot pilot1 = new Pilot("Michael Schumacher"100);
 48InBlock.gif            db.Set(pilot1);
 49InBlock.gif            Console.WriteLine("Stored {0}", pilot1);
 50ExpandedSubBlockEnd.gif        }

 51InBlock.gif    
 52InBlock.gif        public static void StoreSecondPilot(ObjectContainer db)
 53ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 54InBlock.gif            Pilot pilot2 = new Pilot("Rubens Barrichello"99);
 55InBlock.gif            db.Set(pilot2);
 56InBlock.gif            Console.WriteLine("Stored {0}", pilot2);
 57ExpandedSubBlockEnd.gif        }

 58InBlock.gif    
 59InBlock.gif        public static void RetrieveAllPilotQBE(ObjectContainer db) 
 60ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 61InBlock.gif            Pilot proto = new Pilot(null0);
 62InBlock.gif            ObjectSet result = db.Get(proto);
 63InBlock.gif            ListResult(result);
 64ExpandedSubBlockEnd.gif        }

 65InBlock.gif    
 66InBlock.gif        public static void RetrieveAllPilots(ObjectContainer db) 
 67ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 68InBlock.gif            ObjectSet result = db.Get(typeof(Pilot));
 69InBlock.gif            ListResult(result);
 70ExpandedSubBlockEnd.gif        }

 71InBlock.gif    
 72InBlock.gif        public static void RetrievePilotByName(ObjectContainer db)
 73ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 74InBlock.gif            Pilot proto = new Pilot("Michael Schumacher"0);
 75InBlock.gif            ObjectSet result = db.Get(proto);
 76InBlock.gif            ListResult(result);
 77ExpandedSubBlockEnd.gif        }

 78InBlock.gif        
 79InBlock.gif        public static void RetrievePilotByExactPoints(ObjectContainer db)
 80ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 81InBlock.gif            Pilot proto = new Pilot(null100);
 82InBlock.gif            ObjectSet result = db.Get(proto);
 83InBlock.gif            ListResult(result);
 84ExpandedSubBlockEnd.gif        }

 85InBlock.gif    
 86InBlock.gif        public static void UpdatePilot(ObjectContainer db)
 87ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 88InBlock.gif            ObjectSet result = db.Get(new Pilot("Michael Schumacher"0));
 89InBlock.gif            Pilot found = (Pilot)result.Next();
 90InBlock.gif            found.AddPoints(11);
 91InBlock.gif            db.Set(found);
 92InBlock.gif            Console.WriteLine("Added 11 points for {0}", found);
 93InBlock.gif            RetrieveAllPilots(db);
 94ExpandedSubBlockEnd.gif        }

 95InBlock.gif    
 96InBlock.gif        public static void DeleteFirstPilotByName(ObjectContainer db)
 97ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 98InBlock.gif            ObjectSet result = db.Get(new Pilot("Michael Schumacher"0));
 99InBlock.gif            Pilot found = (Pilot)result.Next();
100InBlock.gif            db.Delete(found);
101InBlock.gif            Console.WriteLine("Deleted {0}", found);
102InBlock.gif            RetrieveAllPilots(db);
103ExpandedSubBlockEnd.gif        }

104InBlock.gif    
105InBlock.gif        public static void DeleteSecondPilotByName(ObjectContainer db)
106ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
107InBlock.gif            ObjectSet result = db.Get(new Pilot("Rubens Barrichello"0));
108InBlock.gif            Pilot found = (Pilot)result.Next();
109InBlock.gif            db.Delete(found);
110InBlock.gif            Console.WriteLine("Deleted {0}", found);
111InBlock.gif            RetrieveAllPilots(db);
112ExpandedSubBlockEnd.gif        }

113ExpandedSubBlockEnd.gif    }

114ExpandedBlockEnd.gif}
 
115None.gif

转载于:https://www.cnblogs.com/JackyXu/archive/2006/11/10/557168.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值