Bdb (c) Getting started-Introduction to Berkeley DB

Source: Internet
Author: User

See <installdir>/docs/GSG/C/index.html or the corresponding PDF document.

1. Concepts in bdb

Note: bdb is a value/key database, not a relational database.

Below are several important concepts in bdb:

Records: logically, each record represents a database entry. Each record contains two types of information: Key and data.

Access methods: the access method. Berkeley provides users with multiple access methods to organize database data based on their needs.
Generally, there are two principles for selecting an access method: the method to apply the key first, and the performance to be obtained. To select a specific access method, You must select it when creating the database. Then, all operations will be performed through all the APIS provided by berkeleydb based on this access method. After that, the access method is transparent to users.

Bdb access methods mainly includes: btree, hash, queue, and recno.

Returned value: the bdb API always returns 0 when it succeeds. If it fails, a non-0 value is returned.

2. Database Operations

In bdb, a database is a set of records. Recards contains key-value pairs of key/data in order. In terms of concept, we can regard a database as a table containing two columns. The first column contains a key, and the second column contains data. Both key and data are managed through the DBT struct.

(1) Open the database
To open a database, you must first use the db_creaet () function to initialize a DB handle (handle ). Once the DB handle is initialized, you can use its open () method to open the database.
It should be noted that, by default, if a database does not exist, open will not create its own database. You can specify the db_create flag for open.

(2) shut down the database

When using the database, you need to disable it. Use the close () method. After a database is closed, it cannot be used unless it is opened again. We recommend that you close all opened cursor before closing the database. When the database is closed, the still active cursor will lead to unexpected results, especially if these cursors are performing write operations on the database. Generally, you need to ensure that all database access is completed before you close the database.
When closing the last opened handle of a database, its cache is written to the disk by default. Therefore, you do not need to manually write the cache to the disk. However, you can also use the DB-> sync () method to manually write the cache to the disk.

The following code opens and closes a database:

// gcc 1.c -Iinclude -ldb  -Llib#include <db.h>#include <stdio.h>#include <stdlib.h>DB *dbp;/* DB structure handle */u_int32_t flags;/* database open flags */int ret;/* function return value */void openDB() {/* Initialize the structure. This* database is not opened in an environment,* so the environment pointer is NULL. */ret = db_create(&dbp, NULL, 0);if (ret != 0) {/* Error handling goes here */printf("db_create error.\n");exit(0);}/* Database open flags */flags = DB_CREATE; /* If the database does not exist, create it.*//* open the database */ret = dbp->open(dbp,/* DB structure pointer */NULL,/* Transaction pointer */"my_db.db",/* On-disk file that holds the database. */NULL,/* Optional logical database name */DB_BTREE,/* Database access method */flags,/* Open flags */0);/* File mode (using defaults) */if (ret != 0) {/* Error handling goes here */printf("DB open error.\n");exit(0);}printf("DB open ok.\n");}void closeDB() {/* When we're done with the database, close it. */if (dbp != NULL) {ret=dbp->close(dbp, 0);if (ret != 0) {/* Error handling goes here */printf("DB close error.\n");} else {printf("DB close ok.\n");}} else {printf("handle is NULL, do not use it to close DB.\n");}}int main() {openDB();closeDB();return 0;}

(3) database opening mark
The following describes the basic flags for opening databases. Note that this does not include all flags. For a complete list of flags, see the API documentation. The following mark is required for getting started and for single-threaded database programs.

If you need to use multiple tags, you can use the OR operator (| ).

Db_create: if the database does not exist, create it. By default, if the database does not exist, opening the database fails.
Db_excl: if the database exists, opening the database will fail. Note that this flag is valid only when db_create is used.
Db_rdonly: Open the database in read-only mode. The write operation fails.
Db_truncate: Delete the disk files containing the database physically. As a result, the database deletes all the databases contained in a file.

(4) Database Management Methods

The following dB method is useful only when you manage dB databases.
DB-> get_open_flags (): returns the current open flag. If the database is not opened, an error is returned using this method.
DB-> remove (): deletes the specified database. If the database parameter is not specified, the entire database file will be deleted. Note: If a database has an opened handle, do not delete the database.
DB-> Rename (): Rename the database.

(5) error reporting functions
To simplify Error Reporting and handling, the DB struct provides several useful methods.
Set_errcall ()
Set_errfile ()
Set_errpfx ()
Err ()
Errx ()

(6) use the database in enviroments

3. database records

The DB record contains two parts: one key and some data. The key and its corresponding data are contained in a DBT structure. Therefore, access to a database requires two such structures: Key and data.
The DBT struct provides a void * field to point to your own data, and the other is the data length. Therefore, they can be used to store any content, from basic data types to complex struct, as long as the data is in a continuous memory block.
The following describes how to use DBT and how to save and obtain key/value pairs from the database.

(1) Use Database records
Each database record is composed of two DBT structures, one is the key and the other is the data.
To save a database record, if the key and data are basic data types (INT, float, etc.) or basic data types arrays, we only need to specify the memory location and its length, as shown below:

DBT key, data;
Int Ikey = 10;
Char * idata = "This is data ";

/* Zero out the dbts before using them .*/
Memset (& Key, 0, sizeof (DBT ));
Memset (& Data, 0, sizeof (DBT ));

Key. Data = & Ikey;
Key. size = sizeof (INT );
Data. Data = idata;
Data. size = strlen (idata) + 1;
To obtain a record, you only need to give the void * returned in DBT to the appropriate variable.

(2) read and write database records
When reading and writing database records, pay attention to whether the database supports Repeated Records. If the keys of records of multiple databases are the same, they are considered as duplicate records. A data set with the same key is called a duplicates set ). In dB, a given key is saved only once for the replica set.
By default, duplicate records are not supported in dB databases. If the database supports repeated records, you need to use the cursor to access all records in the repeated set.
DB provides two basic mechanisms to store and obtain database key/data pairs:
DBT-> put () and DBT-> get () provide simple access to non-duplicate data;
Cursor cursor provides many methods to save and retrieve data.
The following describes how to use put and get.
Write records to the database:
DBT-> put ()
The put function provides a flags parameter used to control the write behavior of the database of the DB. A common flag is db_nooverwrite, which disables overwriting of existing records in the database. If the provided key already exists in the database, the put method returns db_keyexist even if the database supports Repeated Records.
Read records from the database:
DBT-> get ()
If the database supports repeated records, this method returns only the first record by default. Therefore, for databases that support Repeated Records, cursor is usually used to obtain records. (Of course, you can also use the overall get, that is, use the db_multiple flag to give the get method, so that it will return all records, but consider that if there are too many records, the memory block needs to be large ).
By default, the get () method returns the first record of key matching. If the database supports repeated records, you can use the db_get_both flag to cause get () returns the first record that matches both the key and data.
If the specified key and/or data do not exist in the Database, get returns db_notfound.
Delete record:
DB-> Del ()
Used to delete records in a database. If the database supports repeated records, all related data will be deleted. If you delete a record from the record, use the cursor.
To delete all records in the database, you can use DB-> truncate ().
(3) use struct in dB
As mentioned above, although dB only has one key and data, data can store any number of data, and multiple data can be saved through struct. As long as the struct field does not have a pointer, it can be stored and read like a simple data type. You only need to set the data address to DBT and the size of DBT.
However, in more cases, the struct may require pointers. For example, if it is a large string, the memory may need to be dynamically allocated. The processing of struct to include pointers is a little more complicated, because DBT must require that its data content be in the continuous memory. If it is a pointer, it points to the heap memory, which is obviously not continuous. Therefore, the solution is to copy data from all the fields of the struct to a temporary struct and then read and write the database.

4.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.