Elektra
0.8.24
|
When programming in Java it is possible to access the kdb database, changing values of existing keys or adding new ones and a few other things. It is also possible to write plugins for elektra in Java but we will focus on using the java binding in this tutorial.
In order to use kdb
you will need include the dependency in your project. Here you can find a detailed tutorial on how to do that.
After that you can start loading an KDB
object as follows:
Note that KDB implements AutoClosable
which allows try-with-resouces.
You can also pass a Key
object with an empty string on the first line. The passed key (user/kdbsession/javabinding
in this case) is being used for the session and stores warnings and error informations.
First I will show how to get a key which was already saved in the database. The first thing we need to do is to create a KeySet
in which our key(s) will be loaded.
Now we load all keys and provide a parent key from which all keys below will be loaded
Now we can simply fetch the desired key's value as follows:
So for example if you have executed before the application starts kdb set user/my/test it_works!
, the method call set.lookup("user/my/test").getString()
would return it_works!
.
Next I will show how to save a new key into the database. First we need need to create an empty KeySet
again. We also need to fetch all keys for the namespace before we will be able to save a new key.
If you try to save a key without fetching it beforehand, a KDBException
will be thrown, telling you to call get before set.
The user namespace is accessible without special rights, but if you try to write to system you will need to have root privileges. Check this to see how to run as non-root user. This should only be done in testing environments though as it is not intended for productive systems.
KeySet
First we create a new KDB
object and fetch all keys for the desired namespace, in this example the user
namespace. Since it saves all keys in our passed set
variable we can then iterate through it by a simple for loop. The at(int)
method gives us the key on the corresponding position which we will print out in this example.