cberkeley-db

How to assign an integer value to "key.data" in Berkeley DB using C


Off lately I am working with Berkeley DB. I have seen examples wherein people have used "string" as values to "key.data" while creating a database using Berkeley DB. I want to assign an integer value to it. How can I do that? Should I create a structure with int member in it or is there any other way possible?

DBT key, data;
memset(&key, 0, sizeof(key));
memset(&data, 0, sizeof(data));
key.data = "fruit";
key.size = sizeof("fruit");

So instead of "fruit" above I want to assign an integer value. Any kind of help would be appreciated.


Solution

  • DBT structures provide a void * field that you use to point to your data, and another field that identifies the data length. They can therefore be used to store anything from simple primitive data to complex structures so long as the information you want to store resides in a single contiguous block of memory.

    See, http://download.oracle.com/docs/cd/E17076_02/html/gsg/C/DBEntry.html

    To store integers, you would assign a pointer to an int to key.data, e.g.:

    int x = 42;
    key.data = &x;
    key.size = sizeof(x);