KVDB 基础示例

该示例主要演示了 KVDB 的基础功能,包括 KV 的获取及设置修改功能。

代码说明

示例代码位于 samples/kvdb_basic_sample.c ,在 main.c 有定义默认的 KV 集合表,在里面有 boot_count KV。通过该 KV 来记录当前系统的启动次数。每次掉电再启动时,该 KV 会自动加一,并保存至 KVDB 中。大致内容如下:

  1. void kvdb_basic_sample(fdb_kvdb_t kvdb)
  2. {
  3. struct fdb_blob blob;
  4. int boot_count = 0;
  5. FDB_INFO("==================== kvdb_basic_sample ====================\n");
  6. { /* GET the KV value */
  7. /* get the "boot_count" KV value */
  8. fdb_kv_get_blob(kvdb, "boot_count", fdb_blob_make(&blob, &boot_count, sizeof(boot_count)));
  9. /* the blob.saved.len is more than 0 when get the value successful */
  10. if (blob.saved.len > 0) {
  11. FDB_INFO("get the 'boot_count' value is %d\n", boot_count);
  12. } else {
  13. FDB_INFO("get the 'boot_count' failed\n");
  14. }
  15. }
  16. { /* CHANGE the KV value */
  17. /* increase the boot count */
  18. boot_count ++;
  19. /* change the "boot_count" KV's value */
  20. fdb_kv_set_blob(kvdb, "boot_count", fdb_blob_make(&blob, &boot_count, sizeof(boot_count)));
  21. FDB_INFO("set the 'boot_count' value to %d\n", boot_count);
  22. }
  23. FDB_INFO("===========================================================\n");
  24. }

首次运行日志

当前 boot_count 为 0 ,对其加一后,存入数据库。

  1. [FlashDB][sample][kvdb][basic] ==================== kvdb_basic_sample ====================
  2. [FlashDB][sample][kvdb][basic] get the 'boot_count' value is 0
  3. [FlashDB][sample][kvdb][basic] set the 'boot_count' value to 1
  4. [FlashDB][sample][kvdb][basic] ===========================================================

二次运行日志

当前 boot_count 为 1 ,说明上次的保存生效了,再对其加一后保存,供下次访问使用。

  1. [FlashDB][sample][kvdb][basic] ==================== kvdb_basic_sample ====================
  2. [FlashDB][sample][kvdb][basic] get the 'boot_count' value is 1
  3. [FlashDB][sample][kvdb][basic] set the 'boot_count' value to 2
  4. [FlashDB][sample][kvdb][basic] ===========================================================