Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6658348
  • 博文数量: 915
  • 博客积分: 17977
  • 博客等级: 上将
  • 技术积分: 8846
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-26 09:59
个人简介

一个好老好老的老程序员了。

文章分类

全部博文(915)

文章存档

2022年(9)

2021年(13)

2020年(10)

2019年(40)

2018年(88)

2017年(130)

2015年(5)

2014年(12)

2013年(41)

2012年(36)

2011年(272)

2010年(1)

2009年(53)

2008年(65)

2007年(47)

2006年(81)

2005年(12)

分类: NOSQL

2013-10-22 22:19:52

上接:  地址:http://blog.chinaunix.net/uid-78707-id-3931335.html
七:Java编程访问数据库(续)
昨天建立了连接并得到了集合空间和集合,今天实现了集合查询。完整代码如下:

点击(此处)折叠或打开

  1. package com.greencloud;

  2. import org.bson.BSONObject;
  3. import org.bson.BasicBSONObject;

  4. import com.sequoiadb.base.CollectionSpace;
  5. import com.sequoiadb.base.DBCollection;
  6. import com.sequoiadb.base.DBCursor;
  7. import com.sequoiadb.base.Sequoiadb;
  8. import com.sequoiadb.exception.BaseException;

  9. public class SequoiaDbDemo {

  10.     static String CS_NAME = "foo";
  11.     static String CL_NAME = "bar";
  12.     static String INDEX_NAME = "bar";

  13.     /**
  14.      * @param args
  15.      */
  16.     public static void main(String[] args) {
  17.         // TODO Auto-generated method stub
  18.         String connectStr = "192.168.8.128:50000";
  19.         Sequoiadb sdb = null;
  20.         try {
  21.             sdb = new Sequoiadb(connectStr, "sdbadmin", "sdbadmin");
  22.         } catch (BaseException be) {
  23.             System.out.println(be.toString());
  24.             be.printStackTrace();
  25.             System.exit(1);
  26.         }

  27.         CollectionSpace cs = null;
  28.         if (sdb.isCollectionSpaceExist(CS_NAME)) {
  29.             cs = sdb.getCollectionSpace(CS_NAME);
  30.             System.out.println("Select Collection Space");
  31.         } else {
  32.             cs = sdb.createCollectionSpace(CS_NAME);
  33.             System.out.println("Create Collection Space");
  34.         }

  35.         DBCollection cl = null;
  36.         if (cs.isCollectionExist(CL_NAME)) {
  37.             cl = cs.getCollection(CL_NAME);
  38.             System.out.println("Select Colleciton");
  39.         } else {
  40.             cl = cs.createCollection(CL_NAME);
  41.             System.out.println("Create Collection");
  42.         }

  43.         try {
  44.             BSONObject index = null;
  45.             DBCursor indexCursor = cl.getIndex(INDEX_NAME);
  46.             if (indexCursor.hasNext()) {
  47.                 index = indexCursor.getNext();
  48.             }
  49.             // result cursor
  50.             DBCursor dataCursor = null;
  51.             // 构建相应BSONObject,用于查询,包括:条件(query),域选择(selector),排序规则(orderBy),
  52.             // 索引使用(index),跳过记录个数(0),返回记录个数(-1:返回所有数据)。
  53.             // query condition
  54.             BSONObject query = new BasicBSONObject();
  55.             BSONObject condition = new BasicBSONObject();
  56.             condition.put("$et", "wangcc");
  57.             // condition.put("$lte", 9);
  58.             query.put("name", condition);
  59.             // return fields
  60.             BSONObject selector = new BasicBSONObject();
  61.             selector.put("_id", null);
  62.             selector.put("name", null);
  63.             selector.put("age", 0);
  64.             // order by ASC(1)/DESC(-1)
  65.             BSONObject orderBy = new BasicBSONObject();
  66.             orderBy.put("_id", -1);
  67.             if (index == null) {
  68.                 dataCursor = cl.query(query, selector, orderBy, null, 0, -1);
  69.             }
  70.             // or
  71.             // dataCursor = cl.query("{'Id':{'$gte':0,'$lte':9}}",
  72.             // "{'Id':null,'Age':null}", "{'Id':-1}", null, 0, -1);
  73.             else {
  74.                 dataCursor = cl.query(query, selector, orderBy, index, 0, -1);
  75.             }
  76.             // or
  77.             // dataCursor = cl.query("{'Id':{'$gte':0,'$lte':9}}",
  78.             // "{'Id':null,'Age':null}", "{'Id':-1}", index, 0, -1);
  79.             // 使用Cursor游标,进行查询结果遍历
  80.             // operate data by cursor
  81.             while (dataCursor.hasNext()) {
  82.                 System.out.println(dataCursor.getNext());
  83.             }
  84.             // get count by match condition
  85.             long count = cl.getCount(query);
  86.             System.out.println("Get count by condition: " + query
  87.                     + ", count = " + count);
  88.         } catch (BaseException e) {
  89.             e.printStackTrace();
  90.         }
  91.     }
  92. }
其中从第51行到98行是查询的语句。由于创建时没有使用索引,55行和82行不会执行。执行结果会输出两行记录,和条件,总数为2(即90行和94行的输出)。上述程序的输出结果为:

点击(此处)折叠或打开

  1. Select Collection Space
  2. Select Colleciton
  3. { "_id" : { "$oid" : "52582e1547c0437e0b000001"} , "age" : 36 , "name" : "wangcc"}
  4. { "_id" : { "$oid" : "52582e0247c0437e0b000000"} , "age" : 0 , "name" : "wangcc"}
  5. Get count by condition: { "name" : { "$et" : "wangcc"}}, count = 2
BSONObject selector是查询的字段,put方法第一个是字段名,第二个是默认值。
我的Sequoiadb数据库的情况是(通过sdb查询):

点击(此处)折叠或打开

  1. > var sdb = new Sdb("localhost",50000)
  2. Takes 1.4294179166s.
  3. > sdb.exec("select * from foo.bar")
  4. {
  5.   "_id": {
  6.     "$oid": "52582e0247c0437e0b000000"
  7.   },
  8.   "name": "wangcc"
  9. }
  10. {
  11.   "_id": {
  12.     "$oid": "52582e1547c0437e0b000001"
  13.   },
  14.   "name": "wangcc",
  15.   "age": 36,
  16.   "phone": "123456"
  17. }
  18. Return 2 row(s).
  19. Takes 1.4294724560s.
八、Java编程访问数据库(续)
昨天完成了数据库的查询,今天(11月23日)完成数据库的添加。代码是在昨天的基础上修改的,修改一:将查询部分单独提出一个方法叫Query,修改二:查询调价全部查询;代码如下:

点击(此处)折叠或打开

  1. package com.greencloud;

  2. import org.bson.BSONObject;
  3. import org.bson.BasicBSONObject;

  4. import com.sequoiadb.base.CollectionSpace;
  5. import com.sequoiadb.base.DBCollection;
  6. import com.sequoiadb.base.DBCursor;
  7. import com.sequoiadb.base.Sequoiadb;
  8. import com.sequoiadb.exception.BaseException;

  9. public class SequoiaDbDemo {

  10.     static String CS_NAME = "foo";
  11.     static String CL_NAME = "bar";
  12.     static String INDEX_NAME = "bar";

  13.     /**
  14.      * @param args
  15.      */
  16.     public static void main(String[] args) {
  17.         // TODO Auto-generated method stub
  18.         String connectStr = "192.168.8.128:50000";
  19.         Sequoiadb sdb = null;
  20.         try {
  21.             sdb = new Sequoiadb(connectStr, "sdbadmin", "sdbadmin");
  22.         } catch (BaseException be) {
  23.             System.out.println(be.toString());
  24.             be.printStackTrace();
  25.             System.exit(1);
  26.         }

  27.         CollectionSpace cs = null;
  28.         if (sdb.isCollectionSpaceExist(CS_NAME)) {
  29.             cs = sdb.getCollectionSpace(CS_NAME);
  30.             System.out.println("Select Collection Space");
  31.         } else {
  32.             cs = sdb.createCollectionSpace(CS_NAME);
  33.             System.out.println("Create Collection Space");
  34.         }

  35.         DBCollection cl = null;
  36.         if (cs.isCollectionExist(CL_NAME)) {
  37.             cl = cs.getCollection(CL_NAME);
  38.             System.out.println("Select Colleciton");
  39.         } else {
  40.             cl = cs.createCollection(CL_NAME);
  41.             System.out.println("Create Collection");
  42.         }
  43.         System.out.println("Before Insert");
  44.         Query(cl);
  45.         System.out.println("\r\nStart Insert");
  46.         Insert(cl);
  47.         System.out.println("\r\nAfter Insert");
  48.         Query(cl);
  49.     }

  50.     static void Insert(DBCollection cl) {
  51.         BSONObject insertor1 = new BasicBSONObject();
  52.         insertor1.put("name", "wanghg");
  53.         insertor1.put("age", "32");
  54.         insertor1.put("sex", "nan");
  55.         BSONObject insertor2 = new BasicBSONObject();
  56.         insertor2.put("name", "hao-yu");
  57.         insertor2.put("age", "26");
  58.         insertor2.put("jiguan", "benxi");
  59.         try {
  60.             cl.insert(insertor1);
  61.             cl.insert(insertor2);
  62.         } catch (BaseException be) {
  63.             System.out.println("Failed to insert chinese record, ErrorType = "
  64.                     + be.getErrorType());
  65.         } catch (Exception e) {
  66.             e.printStackTrace();
  67.         }
  68.     }

  69.     static void Query(DBCollection cl) {
  70.         try {
  71.             BSONObject index = null;
  72.             DBCursor indexCursor = cl.getIndex(INDEX_NAME);
  73.             if (indexCursor.hasNext()) {
  74.                 index = indexCursor.getNext();
  75.             }
  76.             // result cursor
  77.             DBCursor dataCursor = null;
  78.             // 构建相应BSONObject,用于查询,包括:条件(query),域选择(selector),排序规则(orderBy)
  79.             // 索引使用(index),跳过记录个数(0),返回记录个数(-1:返回所有数据)
  80.             // query condition
  81.             BSONObject query = new BasicBSONObject();
  82.             // 删除查询条件,查询所有记录
  83.             //BSONObject condition = new BasicBSONObject();
  84.             //condition.put("$et", "wangcc");
  85.             // condition.put("$lte", 9);
  86.             //query.put("name", condition);
  87.             // return fields
  88.             BSONObject selector = new BasicBSONObject();
  89.             selector.put("_id", null);
  90.             selector.put("name", null);
  91.             selector.put("age", 0);
  92.             // order by ASC(1)/DESC(-1)
  93.             BSONObject orderBy = new BasicBSONObject();
  94.             orderBy.put("_id", -1);
  95.             if (index == null) {
  96.                 dataCursor = cl.query(query, selector, orderBy, null, 0, -1);
  97.             }
  98.             // or
  99.             // dataCursor = cl.query("{'Id':{'$gte':0,'$lte':9}}",
  100.             // "{'Id':null,'Age':null}", "{'Id':-1}", null, 0, -1);
  101.             else {
  102.                 dataCursor = cl.query(query, selector, orderBy, index, 0, -1);
  103.             }
  104.             // or
  105.             // dataCursor = cl.query("{'Id':{'$gte':0,'$lte':9}}",
  106.             // "{'Id':null,'Age':null}", "{'Id':-1}", index, 0, -1);
  107.             // 使用Cursor游标,进行查询结果遍历
  108.             // operate data by cursor
  109.             while (dataCursor.hasNext()) {
  110.                 System.out.println(dataCursor.getNext());
  111.             }
  112.             // get count by match condition
  113.             long count = cl.getCount(query);
  114.             System.out.println("Get count by condition: " + query
  115.                     + ", count = " + count);
  116.         } catch (BaseException e) {
  117.             e.printStackTrace();
  118.         }
  119.     }
  120. }
运行效果如下:

点击(此处)折叠或打开

  1. Select Collection Space
  2. Select Colleciton
  3. Before Insert
  4. { "_id" : { "$oid" : "52582e1547c0437e0b000001"} , "age" : 36 , "name" : "wangcc"}
  5. { "_id" : { "$oid" : "52582e0247c0437e0b000000"} , "age" : 0 , "name" : "wangcc"}
  6. Get count by condition: { }, count = 2

  7. Start Insert

  8. After Insert
  9. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb117"} , "age" : "26" , "name" : "hao-yu"}
  10. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb116"} , "age" : "32" , "name" : "wanghg"}
  11. { "_id" : { "$oid" : "52582e1547c0437e0b000001"} , "age" : 36 , "name" : "wangcc"}
  12. { "_id" : { "$oid" : "52582e0247c0437e0b000000"} , "age" : 0 , "name" : "wangcc"}
  13. Get count by condition: { }, count = 4
使用sdb shell在执行插入后查询结果:

点击(此处)折叠或打开

  1. > sdb.exec("select * from foo.bar")
  2. {
  3.   "_id": {
  4.     "$oid": "52582e0247c0437e0b000000"
  5.   },
  6.   "name": "wangcc"
  7. }
  8. {
  9.   "_id": {
  10.     "$oid": "52582e1547c0437e0b000001"
  11.   },
  12.   "name": "wangcc",
  13.   "age": 36,
  14.   "phone": "123456"
  15. }
  16. {
  17.   "_id": {
  18.     "$oid": "5267d1f7b5b7332e021fb116"
  19.   },
  20.   "name": "wanghg",
  21.   "age": "32",
  22.   "sex": "nan"
  23. }
  24. {
  25.   "_id": {
  26.     "$oid": "5267d1f7b5b7332e021fb117"
  27.   },
  28.   "name": "hao-yu",
  29.   "age": "26",
  30.   "jiguan": "benxi"
  31. }
  32. Return 4 row(s).
  33. Takes 0.2951s.
  34. >   
九、Java编程访问数据库(续)
之前实现了数据库的查询与插入,今天(10月24日)实现数据库的更新操作,源码如下:

点击(此处)折叠或打开

  1. package com.greencloud;

  2. import org.bson.BSONObject;
  3. import org.bson.BasicBSONObject;

  4. import com.sequoiadb.base.CollectionSpace;
  5. import com.sequoiadb.base.DBCollection;
  6. import com.sequoiadb.base.DBCursor;
  7. import com.sequoiadb.base.Sequoiadb;
  8. import com.sequoiadb.exception.BaseException;

  9. public class SequoiaDbDemo {

  10.     static String CS_NAME = "foo";
  11.     static String CL_NAME = "bar";
  12.     static String INDEX_NAME = "bar";

  13.     /**
  14.      * @param args
  15.      */
  16.     public static void main(String[] args) {
  17.         // TODO Auto-generated method stub
  18.         String connectStr = "192.168.8.128:50000";
  19.         Sequoiadb sdb = null;
  20.         try {
  21.             sdb = new Sequoiadb(connectStr, "sdbadmin", "sdbadmin");
  22.         } catch (BaseException be) {
  23.             System.out.println(be.toString());
  24.             be.printStackTrace();
  25.             System.exit(1);
  26.         }

  27.         CollectionSpace cs = null;
  28.         if (sdb.isCollectionSpaceExist(CS_NAME)) {
  29.             cs = sdb.getCollectionSpace(CS_NAME);
  30.             System.out.println("Select Collection Space");
  31.         } else {
  32.             cs = sdb.createCollectionSpace(CS_NAME);
  33.             System.out.println("Create Collection Space");
  34.         }

  35.         DBCollection cl = null;
  36.         if (cs.isCollectionExist(CL_NAME)) {
  37.             cl = cs.getCollection(CL_NAME);
  38.             System.out.println("Select Colleciton");
  39.         } else {
  40.             cl = cs.createCollection(CL_NAME);
  41.             System.out.println("Create Collection");
  42.         }
  43.         System.out.println("Before Insert");
  44.         Query(cl);
  45.         // System.out.println("\r\nStart Insert");
  46.         // Insert(cl);
  47.         System.out.println("\r\nStart Update");
  48.         Update(cl);
  49.         System.out.println("\r\nAfter Insert");
  50.         Query(cl);
  51.     }

  52.     static void Insert(DBCollection cl) {
  53.         BSONObject insertor1 = new BasicBSONObject();
  54.         insertor1.put("name", "wanghg");
  55.         insertor1.put("age", "32");
  56.         insertor1.put("sex", "nan");
  57.         BSONObject insertor2 = new BasicBSONObject();
  58.         insertor2.put("name", "hao-yu");
  59.         insertor2.put("age", "26");
  60.         insertor2.put("jiguan", "benxi");
  61.         try {
  62.             cl.insert(insertor1);
  63.             cl.insert(insertor2);
  64.         } catch (BaseException be) {
  65.             System.out.println("Failed to insert chinese record, ErrorType = "
  66.                     + be.getErrorType());
  67.         } catch (Exception e) {
  68.             e.printStackTrace();
  69.         }
  70.     }

  71.     static void Update(DBCollection cl) {
  72.         BSONObject matcher = new BasicBSONObject();
  73.         BSONObject modifier = new BasicBSONObject();
  74.         BSONObject m = new BasicBSONObject();
  75.         matcher.put("name", "wangcc"); // 条件
  76.         m.put("age", 37); // 更新值
  77.         modifier.put("$set", m); // $set,设置指定字段值

  78.         // 更新操作,如果没有满足matcher的条件,则插入记录
  79.         cl.upsert(matcher, modifier, null);
  80.         DBCursor cursor = cl.query(matcher, null, null, null);
  81.         if (cursor.hasNext()) {
  82.             System.out.println(cursor.getNext());
  83.         }
  84.     }

  85.     static void Query(DBCollection cl) {
  86.         try {
  87.             BSONObject index = null;
  88.             DBCursor indexCursor = cl.getIndex(INDEX_NAME);
  89.             if (indexCursor.hasNext()) {
  90.                 index = indexCursor.getNext();
  91.             }
  92.             // result cursor
  93.             DBCursor dataCursor = null;
  94.             // 构建相应BSONObject,用于查询,包括:条件(query),域选择(selector),排序规则(orderBy),
  95.             // 索引使用(index),跳过记录个数(0),返回记录个数(-1:返回所有数据)。
  96.             // query condition
  97.             BSONObject query = new BasicBSONObject();
  98.             // 删除查询条件,查询所有记录
  99.             // BSONObject condition = new BasicBSONObject();
  100.             // condition.put("$et", "wangcc");
  101.             // condition.put("$lte", 9);
  102.             // query.put("name", condition);
  103.             // return fields
  104.             BSONObject selector = new BasicBSONObject();
  105.             selector.put("_id", null);
  106.             selector.put("name", null);
  107.             selector.put("age", 0);
  108.             // order by ASC(1)/DESC(-1)
  109.             BSONObject orderBy = new BasicBSONObject();
  110.             orderBy.put("_id", -1);
  111.             if (index == null) {
  112.                 dataCursor = cl.query(query, selector, orderBy, null, 0, -1);
  113.             }
  114.             // or
  115.             // dataCursor = cl.query("{'Id':{'$gte':0,'$lte':9}}",
  116.             // "{'Id':null,'Age':null}", "{'Id':-1}", null, 0, -1);
  117.             else {
  118.                 dataCursor = cl.query(query, selector, orderBy, index, 0, -1);
  119.             }
  120.             // or
  121.             // dataCursor = cl.query("{'Id':{'$gte':0,'$lte':9}}",
  122.             // "{'Id':null,'Age':null}", "{'Id':-1}", index, 0, -1);
  123.             // 使用Cursor游标,进行查询结果遍历
  124.             // operate data by cursor
  125.             while (dataCursor.hasNext()) {
  126.                 System.out.println(dataCursor.getNext());
  127.             }
  128.             // get count by match condition
  129.             long count = cl.getCount(query);
  130.             System.out.println("Get count by condition: " + query
  131.                     + ", count = " + count);
  132.         } catch (BaseException e) {
  133.             e.printStackTrace();
  134.         }
  135.     }
  136. }
运行结果如下,看到age已经发生了变化:

点击(此处)折叠或打开

  1. Select Collection Space
  2. Select Colleciton
  3. Before Insert
  4. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb117"} , "age" : "26" , "name" : "hao-yu"}
  5. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb116"} , "age" : "32" , "name" : "wanghg"}
  6. { "_id" : { "$oid" : "52582e1547c0437e0b000001"} , "age" : 36 , "name" : "wangcc"}
  7. { "_id" : { "$oid" : "52582e0247c0437e0b000000"} , "age" : 0 , "name" : "wangcc"}
  8. Get count by condition: { }, count = 4

  9. Start Update
  10. { "Age" : 37 , "_id" : { "$oid" : "52582e0247c0437e0b000000"} , "age" : 37 , "name" : "wangcc"}

  11. After Insert
  12. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb117"} , "age" : "26" , "name" : "hao-yu"}
  13. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb116"} , "age" : "32" , "name" : "wanghg"}
  14. { "_id" : { "$oid" : "52582e1547c0437e0b000001"} , "age" : 37 , "name" : "wangcc"}
  15. { "_id" : { "$oid" : "52582e0247c0437e0b000000"} , "age" : 37 , "name" : "wangcc"}
  16. Get count by condition: { }, count = 4
注意了,在SequoiaDB中,字段名是区分大小写的,我第一次运行的时候代码中m.put("age", 37); 中写的是m.put("Age", 37);在我的数据中就增加了一个Age属性,并没有更新我原有的age属性,所以是区分大小写的。
十、Java编程访问数据库(续)
前两天完成了通过Java编写查询,插入和更新,今天(10月25日)完成最后一个操作,删除。源程序如下:
点击(此处)折叠或打开
  1. package com.greencloud;

  2. import org.bson.BSONObject;
  3. import org.bson.BasicBSONObject;

  4. import com.sequoiadb.base.CollectionSpace;
  5. import com.sequoiadb.base.DBCollection;
  6. import com.sequoiadb.base.DBCursor;
  7. import com.sequoiadb.base.Sequoiadb;
  8. import com.sequoiadb.exception.BaseException;

  9. public class SequoiaDbDemo {

  10.     static String CS_NAME = "foo";
  11.     static String CL_NAME = "bar";
  12.     static String INDEX_NAME = "bar";

  13.     /**
  14.      * @param args
  15.      */
  16.     public static void main(String[] args) {
  17.         // TODO Auto-generated method stub
  18.         String connectStr = "192.168.8.128:50000";
  19.         Sequoiadb sdb = null;
  20.         try {
  21.             sdb = new Sequoiadb(connectStr, "sdbadmin", "sdbadmin");
  22.         } catch (BaseException be) {
  23.             System.out.println(be.toString());
  24.             be.printStackTrace();
  25.             System.exit(1);
  26.         }

  27.         CollectionSpace cs = null;
  28.         if (sdb.isCollectionSpaceExist(CS_NAME)) {
  29.             cs = sdb.getCollectionSpace(CS_NAME);
  30.             System.out.println("Select Collection Space");
  31.         } else {
  32.             cs = sdb.createCollectionSpace(CS_NAME);
  33.             System.out.println("Create Collection Space");
  34.         }

  35.         DBCollection cl = null;
  36.         if (cs.isCollectionExist(CL_NAME)) {
  37.             cl = cs.getCollection(CL_NAME);
  38.             System.out.println("Select Colleciton");
  39.         } else {
  40.             cl = cs.createCollection(CL_NAME);
  41.             System.out.println("Create Collection");
  42.         }
  43.         System.out.println("Before Insert");
  44.         Query(cl);
  45.         // System.out.println("\r\nStart Insert");
  46.         // Insert(cl);
  47.         // System.out.println("\r\nAfter Insert");
  48.         // System.out.println("\r\nStart Update");
  49.         // Update(cl);
  50.         // System.out.println("\r\nAfter Update");
  51.         System.out.println("\r\nStart Delete");
  52.         Delete(cl);
  53.         System.out.println("\r\nAfter Delete");
  54.         Query(cl);
  55.         // CLose Connection
  56.         sdb.disconnect();
  57.     }

  58.     static void Insert(DBCollection cl) {
  59.         BSONObject insertor1 = new BasicBSONObject();
  60.         insertor1.put("name", "wanghg");
  61.         insertor1.put("age", "32");
  62.         insertor1.put("sex", "nan");
  63.         BSONObject insertor2 = new BasicBSONObject();
  64.         insertor2.put("name", "hao-yu");
  65.         insertor2.put("age", "26");
  66.         insertor2.put("jiguan", "benxi");
  67.         try {
  68.             cl.insert(insertor1);
  69.             cl.insert(insertor2);
  70.         } catch (BaseException be) {
  71.             System.out.println("Failed to insert chinese record, ErrorType = "
  72.                     + be.getErrorType());
  73.         } catch (Exception e) {
  74.             e.printStackTrace();
  75.         }
  76.     }

  77.     static void Delete(DBCollection cl) {
  78.         // 构建相应BSONObject,用于设置删除的条件或者使用相对应BSON的String表示
  79.         // create the delete condition
  80.         BSONObject condition = new BasicBSONObject();
  81.         condition.put("name", "wanghg");
  82.         try {
  83.             cl.delete(condition);
  84.             // if you want to delete all the data in current collection, you can
  85.             // use like: cl.delete(null)
  86.             // or
  87.             // cl.delete("{'name':'wanghg'}");
  88.         } catch (BaseException e) {
  89.             System.out
  90.                     .println("Failed to delete data, condition: " + condition);
  91.             e.printStackTrace();
  92.         }
  93.         System.out.println("Delete data successfully");
  94.     }

  95.     static void Update(DBCollection cl) {
  96.         BSONObject matcher = new BasicBSONObject();
  97.         BSONObject modifier = new BasicBSONObject();
  98.         BSONObject m = new BasicBSONObject();
  99.         matcher.put("name", "wangcc"); // 条件
  100.         m.put("age", 37); // 更新值
  101.         modifier.put("$set", m); // $set,设置指定字段值

  102.         // 更新操作,如果没有满足matcher的条件,则插入记录
  103.         cl.upsert(matcher, modifier, null);
  104.         DBCursor cursor = cl.query(matcher, null, null, null);
  105.         if (cursor.hasNext()) {
  106.             System.out.println(cursor.getNext());
  107.         }
  108.     }

  109.     static void Query(DBCollection cl) {
  110.         try {
  111.             BSONObject index = null;
  112.             DBCursor indexCursor = cl.getIndex(INDEX_NAME);
  113.             if (indexCursor.hasNext()) {
  114.                 index = indexCursor.getNext();
  115.             }
  116.             // result cursor
  117.             DBCursor dataCursor = null;
  118.             // 构建相应BSONObject,用于查询,包括:条件(query),域选择(selector),排序规则(orderBy),
  119.             // 索引使用(index),跳过记录个数(0),返回记录个数(-1:返回所有数据)。
  120.             // query condition
  121.             BSONObject query = new BasicBSONObject();
  122.             // 删除查询条件,查询所有记录
  123.             // BSONObject condition = new BasicBSONObject();
  124.             // condition.put("$et", "wangcc");
  125.             // condition.put("$lte", 9);
  126.             // query.put("name", condition);
  127.             // return fields
  128.             BSONObject selector = new BasicBSONObject();
  129.             selector.put("_id", null);
  130.             selector.put("name", null);
  131.             selector.put("age", 0);
  132.             // order by ASC(1)/DESC(-1)
  133.             BSONObject orderBy = new BasicBSONObject();
  134.             orderBy.put("_id", -1);
  135.             if (index == null) {
  136.                 dataCursor = cl.query(query, selector, orderBy, null, 0, -1);
  137.             }
  138.             // or
  139.             // dataCursor = cl.query("{'Id':{'$gte':0,'$lte':9}}",
  140.             // "{'Id':null,'Age':null}", "{'Id':-1}", null, 0, -1);
  141.             else {
  142.                 dataCursor = cl.query(query, selector, orderBy, index, 0, -1);
  143.             }
  144.             // or
  145.             // dataCursor = cl.query("{'Id':{'$gte':0,'$lte':9}}",
  146.             // "{'Id':null,'Age':null}", "{'Id':-1}", index, 0, -1);
  147.             // 使用Cursor游标,进行查询结果遍历
  148.             // operate data by cursor
  149.             while (dataCursor.hasNext()) {
  150.                 System.out.println(dataCursor.getNext());
  151.             }
  152.             // get count by match condition
  153.             long count = cl.getCount(query);
  154.             System.out.println("Get count by condition: " + query
  155.                     + ", count = " + count);
  156.         } catch (BaseException e) {
  157.             e.printStackTrace();
  158.         }
  159.     }
  160. }
运行结果如下:
点击(此处)折叠或打开
  1. Select Collection Space
  2. Select Colleciton
  3. Before Insert
  4. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb117"} , "age" : "26" , "name" : "hao-yu"}
  5. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb116"} , "age" : "32" , "name" : "wanghg"}
  6. { "_id" : { "$oid" : "52582e1547c0437e0b000001"} , "age" : 37 , "name" : "wangcc"}
  7. { "_id" : { "$oid" : "52582e0247c0437e0b000000"} , "age" : 37 , "name" : "wangcc"}
  8. Get count by condition: { }, count = 4

  9. Start Delete
  10. Delete data successfully

  11. After Delete
  12. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb117"} , "age" : "26" , "name" : "hao-yu"}
  13. { "_id" : { "$oid" : "52582e1547c0437e0b000001"} , "age" : 37 , "name" : "wangcc"}
  14. { "_id" : { "$oid" : "52582e0247c0437e0b000000"} , "age" : 37 , "name" : "wangcc"}
  15. Get count by condition: { }, count = 3
至此,通过Java语言对SequoiaDB进行增删改差(ADUC)操作的列子全部完成了。其实我们还可以通过Sequoiadb类的exec(或者execUpdate)来进行类SQL操作,这里不再赘述,如果感兴趣的朋友可以自己参照信息中心文档来编写,代码很简单的。
在随后的几天,将动手讲解SequoiaDB的备份和恢复。
十一、数据库备份sdbexprt
在现在的计算机环境中,由于各种原因,如非法关机,病毒入侵都造成数据损坏是经常碰到的事情,所以数据备份就显得尤为重要了啊。SequoiaDB提供了备份命令来备份你的数据库。这个命令就是sdbexprt。详细的说明如下:
sdbexprt
sdbexprt是一个实用的工具。它可以从SequoiaDB数据库导出一个JSON格式或者CSV格式的数据存储文件。
选项
参数描述
--help,-h 返回基本帮助和用法文本 。
--hostname,-h 从指定主机名的 SequoiaDB 中导出数据。默认情况下 sdbexprt 尝试连接到
本地主机 。
--svcname,-p 指定的端口号。默认情况下 sdbexprt 尝试连接到端口号 50000 的主机 。
--type,-t 指定的导出数据格式。数据格式可以是 CSV ,或是 JSON 。
--output,-o 指定要导出的文件名。注意:不需要写扩展名 。
--delfield,-e 指定字段分隔符。默认是 ', ', JSON 格式无效。
--delrecord,-r 指定记录分隔符。默认是' \n '。
--fieldlist,-f 指定一个或多个字段来导出数据,使用逗号分隔多个字段。
--fieldincluded,-i 指定是否导出字段名,JSON格式无效。
--csname,-c 指定导出数据的集合空间名。
--clname,-l 指定导出数的的集合名。
用法
在下面的例子,sdbexprt从本地数据库端口50000中导出集合空间foo的集合bar的数据,导出类型是
csv,导出文件为contact,导出字段是 field1和field2。
点击(此处)折叠或打开
  1. sdbexprt –s localhost –p 50000 –t csv –o contace –f field1,field2 –c foo –l bar
但是我在我本机执行数据库的备份时,不管-l的参数指定为bar或者foo.bar,都报错误。我是配置的独立启动模式。
错误信息如下:

点击(此处)折叠或打开

  1. 2013-10-12-04.33.56.361760 Level:ERROR
  2. PID:9660 TID:9660
  3. Function:getCollection Line:511
  4. File:SequoiaDB/engine/pmd/sdbexprt.cpp
  5. Message:
  6. Failed to get collection foo.bar, rc = -75


  7. 2013-10-12-04.34.08.903027 Level:ERROR
  8. PID:9662 TID:9662
  9. Function:getCollection Line:511
  10. File:SequoiaDB/engine/pmd/sdbexprt.cpp
  11. Message:
  12. Failed to get collection bar, rc = -75
从信息查看,是找不到集合bar(foo.bar),可这个集合明明是存在的,请看sdb命令输出:
点击(此处)折叠或打开
  1. > sdb.listCollectionSpaces()
  2. {
  3.   "Name": "foo"
  4. }
  5. Return 1 row(s).
  6. Takes 0.94698s.
  7. > sdb.listCollections()
  8. {
  9.   "Name": "foo.bar"
  10. }
  11. Return 1 row(s).
  12. Takes 0.31478s.
  13. >
已经向官方的服务人员提出了疑问,不知道下周能不能给个解答。

11月29日,官方人员给出了解释,是因为1.3版本的导入导出程序有Bug,官方人员给了我最想新的一个版本,经测试,正常。
步骤如下,
将压缩包上传至/opt/sequoiadb/bin目录,然后执行tar -zxvf sdb.tar.gz,解压后会覆盖就的备份恢复命令。
执行过程如下:

点击(此处)折叠或打开

  1. root@ubuntu:/opt/sequoiadb/bin# ./sdbexprt --help
  2. Command options:
  3.   --help help
  4.   -h [ --hostname ] arg database host name
  5.   -s [ --svcname ] arg database service name
  6.   -a [ --delchar ] arg string delimiter ( default: " )
  7.   -e [ --delfield ] arg field delimiter ( default: , )
  8.   -r [ --delrecord ] arg record delimiter ( default: '\n' )
  9.   -f [ --fieldlist ] arg field list ( separate by , )
  10.   -i [ --fieldincluded ] arg include field names ( default: true )
  11.   -c [ --csname ] arg collection space name
  12.   -l [ --clname ] arg collection name
  13.   --file arg database load file name
  14.   --type arg type of file to load, default: json (json,csv)

  15. root@ubuntu:/opt/sequoiadb/bin# ./sdbexprt -h localhost -s 50000 --file ./foo.bar.csv --type csv -c foo -l bar
  16. Field list is required for CSV file, fields are separated by comma ( ',' )
  17. Export Failed

  18. root@ubuntu:/opt/sequoiadb/bin# ./sdbexprt -h localhost -s 50000 -e'|' -c foo -l
  19.  bar --file ./exprt.json --type json
  20. Export Successfully
  21. Detail in log path: sdbexport.log

  22. root@ubuntu:/opt/sequoiadb/bin# cat exprt.json
  23. { "Age" : 37, "_id" : { "$oid" : "52582e0247c0437e0b000000" }, "age" : 37, "name" : "wangcc" }
  24. { "Age" : 37, "_id" : { "$oid" : "52582e1547c0437e0b000001" }, "age" : 37, "name" : "wangcc", "phone" : "123456" }
  25. { "_id" : { "$oid" : "5267d1f7b5b7332e021fb117" }, "name" : "hao-yu", "age" : "26", "jiguan" : "benxi" }

  26. root@ubuntu:/opt/sequoiadb/bin# ./sdbexprt -h localhost -s 50000 -f Age,age,name,phone,jiguan -c foo -l bar --file ./exprt.csv --type csv
  27. Export Successfully
  28. Detail in log path: sdbexport.log

  29. root@ubuntu:/opt/sequoiadb/bin# cat exprt.csv
  30. "Age","age","name","phone","jiguan"
  31. 37,37,"wangcc",,
  32. 37,37,"wangcc","123456",
  33. ,"26","hao-yu",,"benxi
建议大家使用json格式,从过程中你也许看出来了,到处csv格式时,必须用-f参数明确指出要导出的字段。

导入命令sdbimprt和导出是相反的过程,导入命令的参数如下:

点击(此处)折叠或打开

  1. root@ubuntu:~# cd /opt/sequoiadb/bin
  2. root@ubuntu:/opt/sequoiadb/bin# ./sdbimprt --help
  3. Command options:
  4.   --help help
  5.   -h [ --hostname ] arg database host name
  6.   -s [ --svcname ] arg database service name
  7.   -a [ --delchar ] arg string delimiter ( default:
具体的导入过程如下图所示:

正确的导入到处命令的下载参照如下附件:
sdb.part1.rar
sdb.part2.rar
sdb.part3.rar
sdb.part4.rar
sdb.part5.rar

总结:
至此,SequoiaDB数据的安装,配置(独立模式),通过java对数据库进行增删改查以及使用sdb shell进行查询,数据库的导入导出(备份恢复)的测试基本完成,但由于是虚拟机操作,对性能的测试受限制无法进行,同时次发布版本是社区版,企业版本没法获取,如果需要企业版本可以联系contact@sequoiadb.com以获取发行的企业版本,我没有要求企业版。由于社区版的导入导出命令有缺陷,是在官方人员给与我新的版本后测试成功的,如果需要可以从本附件下载或者联系我获取(也可以联系官方获取)。
通过本次测试,让我对NoSQL技术有了一定的了解,对SequoiaDB数据库的使用有了更进一步的掌握,如果附近的朋友有需要帮助的可以联系我,我会给予一定的支持与帮助,共同推进SequoiaDB数据库的良好发展。
阅读(5573) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

joepayne2013-11-27 12:23:20

版主也搞起巨彬的数据库了