String type KV example

This example mainly demonstrates the related functions of the string KV. As a special KV type, the Key and Value of the string KV are both strings, which are often used in scenarios with high readability requirements such as parameter storage and command storage.

Code description

The sample code is located in samples/kvdb_type_string.c, and a KV named "temp" is used to store the temperature value, which respectively demonstrates the whole process of the string KV from create->read->modify->delete . The general content is as follows:

  1. void kvdb_type_string_sample(fdb_kvdb_t kvdb)
  2. {
  3. FDB_INFO("==================== kvdb_type_string_sample ====================\n");
  4. { /* CREATE new Key-Value */
  5. char temp_data[10] = "36C";
  6. /* It will create new KV node when "temp" KV not in database. */
  7. fdb_kv_set(kvdb, "temp", temp_data);
  8. FDB_INFO("create the 'temp' string KV, value is: %s\n", temp_data);
  9. }
  10. { /* GET the KV value */
  11. char *return_value, temp_data[10] = { 0 };
  12. /* Get the "temp" KV value.
  13. * NOTE: The return value saved in fdb_kv_get's buffer. Please copy away as soon as possible.
  14. */
  15. return_value = fdb_kv_get(kvdb, "temp");
  16. /* the return value is NULL when get the value failed */
  17. if (return_value != NULL) {
  18. strncpy(temp_data, return_value, sizeof(temp_data));
  19. FDB_INFO("get the 'temp' value is: %s\n", temp_data);
  20. }
  21. }
  22. { /* CHANGE the KV value */
  23. char temp_data[10] = "38C";
  24. /* change the "temp" KV's value to "38.1" */
  25. fdb_kv_set(kvdb, "temp", temp_data);
  26. FDB_INFO("set 'temp' value to %s\n", temp_data);
  27. }
  28. { /* DELETE the KV by name */
  29. fdb_kv_del(kvdb, "temp");
  30. FDB_INFO("delete the 'temp' finish\n");
  31. }
  32. FDB_INFO("===========================================================\n");
  33. }

Run log

It can be seen from the log:

  • First create a KV named "temp" and give the initial value 36℃
  • Read the current value of "temp" KV and find that it is the same as the initial value
  • Modify the value of "temp" KV to 38℃
  • Finally delete "temp" KV
  1. [FlashDB][sample][kvdb][string] ==================== kvdb_type_string_sample ====================
  2. [FlashDB][sample][kvdb][string] create the 'temp' string KV, value is: 36C
  3. [FlashDB][sample][kvdb][string] get the 'temp' value is: 36C
  4. [FlashDB][sample][kvdb][string] set 'temp' value to 38C
  5. [FlashDB][sample][kvdb][string] delete the 'temp' finish
  6. [FlashDB][sample][kvdb][string] ===========================================================