1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6 <title>Database Usage Example</title>
7 <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
8 <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
9 <link rel="start" href="index.html" title="Getting Started with Berkeley DB" />
10 <link rel="up" href="DBEntry.html" title="Chapter 3. Database Records" />
11 <link rel="prev" href="cstructs.html" title="Using C Structures with DB" />
12 <link rel="next" href="Cursors.html" title="Chapter 4. Using Cursors" />
15 <div xmlns="" class="navheader">
17 <p>Library Version 11.2.5.3</p>
19 <table width="100%" summary="Navigation header">
21 <th colspan="3" align="center">Database Usage Example</th>
24 <td width="20%" align="left"><a accesskey="p" href="cstructs.html">Prev</a> </td>
25 <th width="60%" align="center">Chapter 3. Database Records</th>
26 <td width="20%" align="right"> <a accesskey="n" href="Cursors.html">Next</a></td>
31 <div class="sect1" lang="en" xml:lang="en">
32 <div class="titlepage">
35 <h2 class="title" style="clear: both"><a id="DbUsage"></a>Database Usage Example</h2>
40 In <a class="xref" href="CoreDbUsage.html" title="Database Example">Database Example</a> we created several
41 functions that will open and close the databases that we will use for
42 our inventory application. We now make use of those functions to load inventory data into
43 the two databases that we use for this application.
46 Again, remember that you can find the complete implementation for these functions
49 <pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_c/getting_started</pre>
51 where <code class="literal"><span class="emphasis"><em>DB_INSTALL</em></span></code> is the location where you
52 placed your DB distribution.
55 <a id="VENDORStruct"></a>
57 <b>Example 3.1 VENDOR Structure</b>
59 <div class="example-contents">
61 We want to store data related to an inventory system. There are two
62 types of information that we want to manage: inventory data and related
63 vendor contact information. To manage this information, we could
64 create a structure for each type of data, but to illustrate
65 storing mixed data without a structure we refrain from creating one
66 for the inventory data.
69 For the vendor data, we add the VENDOR structure to the same file as holds
70 our STOCK_DBS structure. Note that the VENDOR structure uses
71 fixed-length fields. This is not necessary and in fact could
72 represent a waste of resources if the number of vendors stored in
73 our database scales to very large numbers. However, for simplicity we use
74 fixed-length fields anyway, especially
75 given that our sample data contains so few vendor records.
78 Note that for the inventory data, we will store the data by
79 marshaling it into a buffer, described below.
82 <pre class="programlisting">/* File: gettingstarted_common.h */
87 <strong class="userinput"><code>typedef struct vendor {
88 char name[MAXFIELD]; /* Vendor name */
89 char street[MAXFIELD]; /* Street name and number */
90 char city[MAXFIELD]; /* City */
91 char state[3]; /* Two-digit US state code */
92 char zipcode[6]; /* US zipcode */
93 char phone_number[13]; /* Vendor phone number */
94 char sales_rep[MAXFIELD]; /* Name of sales representative */
95 char sales_rep_phone[MAXFIELD]; /* Sales rep's phone number */
96 } VENDOR;</code></strong> </pre>
99 <br class="example-break" />
100 <div class="example">
101 <a id="exampledbload"></a>
103 <b>Example 3.2 example_database_load</b>
105 <div class="example-contents">
107 Our initial sample application will load database information from
108 several flat files. To save space, we won't show all the details of
109 this example program. However, as always you can find the complete
110 implementation for this program here:
112 <pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_c/getting_started</pre>
114 where <code class="literal"><span class="emphasis"><em>DB_INSTALL</em></span></code> is the location where you
115 placed your DB distribution.
118 We begin with the normal include directives and forward declarations:
121 <pre class="programlisting">/* example_database_load.c */
122 #include "gettingstarted_common.h"
124 /* Forward declarations */
125 int load_vendors_database(STOCK_DBS, char *);
126 int pack_string(char *, char *, int);
127 int load_inventory_database(STOCK_DBS, char *); </pre>
129 Next we begin our <code class="function">main()</code> function with the variable
130 declarations and command line parsing that is normal for most command
134 <pre class="programlisting">/*
135 * Loads the contents of vendors.txt and inventory.txt into
136 * Berkeley DB databases.
139 main(int argc, char *argv[])
143 char *basename, *inventory_file, *vendor_file;
145 /* Initialize the STOCK_DBS struct */
146 initialize_stockdbs(&my_stock);
149 * Initialize the base path. This path is used to
150 * identify the location of the flat-text data
156 * Parse the command line arguments here and determine
157 * the location of the flat text files containing the
158 * inventory data here. This step is omitted for clarity.
162 * Identify the files that will hold our databases
163 * This function uses information obtained from the
164 * command line to identify the directory in which
165 * the database files reside.
167 set_db_filenames(&my_stock);
169 /* Find our input files */
170 size = strlen(basename) + strlen(INVENTORY_FILE) + 1;
171 inventory_file = malloc(size);
172 snprintf(inventory_file, size, "%s%s", basename, INVENTORY_FILE);
174 size = strlen(basename) + strlen(VENDORS_FILE) + 1;
175 vendor_file = malloc(size);
176 snprintf(vendor_file, size, "%s%s", basename, VENDORS_FILE);
178 /* Open all databases */
179 ret = databases_setup(&my_stock, "example_database_load", stderr);
181 fprintf(stderr, "Error opening databases\n");
182 databases_close(&my_stock);
186 ret = load_vendors_database(my_stock, vendor_file);
188 fprintf(stderr, "Error loading vendors database.\n");
189 databases_close(&my_stock);
192 ret = load_inventory_database(my_stock, inventory_file);
194 fprintf(stderr, "Error loading inventory database.\n");
195 databases_close(&my_stock);
199 /* close our environment and databases */
200 databases_close(&my_stock);
202 printf("Done loading databases.\n");
206 Notice that there is not a lot to this function because we have pushed
207 off all the database activity to other places. In particular our
208 databases are all opened and configured in
209 <code class="function">databases_setup()</code> which we implemented in
210 <a class="xref" href="CoreDbUsage.html#databasesetup" title="Example 2.4 The databases_setup() Function">The databases_setup() Function</a>.
213 Next we show the implementation of
214 <code class="function">load_vendors_database()</code>. We load this data by
215 scanning (line by line) the contents of the
216 <code class="filename">vendors.txt</code> into a VENDOR structure. Once we have a
217 line scanned into the structure, we can store that structure into our
221 Note that we use the vendor's name as the key here. In doing so, we
222 assume that the vendor's name is unique in our database. If it was not,
223 we would either have to select a different key, or architect our
224 application such that it could cope with multiple vendor records with
228 <pre class="programlisting">/*
229 * Loads the contents of the vendors.txt file into
233 load_vendors_database(STOCK_DBS my_stock, char *vendor_file)
240 /* Open the vendor file for read access */
241 ifp = fopen(vendor_file, "r");
243 fprintf(stderr, "Error opening file '%s'\n", vendor_file);
247 /* Iterate over the vendor file */
248 while(fgets(buf, MAXLINE, ifp) != NULL) {
249 /* zero out the structure */
250 memset(&my_vendor, 0, sizeof(VENDOR));
251 /* Zero out the DBTs */
252 memset(&key, 0, sizeof(DBT));
253 memset(&data, 0, sizeof(DBT));
256 * Scan the line into the structure.
257 * Convenient, but not particularly safe.
258 * In a real program, there would be a lot more
259 * defensive code here.
262 "%20[^#]#%20[^#]#%20[^#]#%3[^#]#%6[^#]#%13[^#]#%20[^#]#%20[^\n]",
263 my_vendor.name, my_vendor.street,
264 my_vendor.city, my_vendor.state,
265 my_vendor.zipcode, my_vendor.phone_number,
266 my_vendor.sales_rep, my_vendor.sales_rep_phone);
269 * Now that we have our structure we can load it
273 /* Set up the database record's key */
274 key.data = my_vendor.name;
275 key.size = strlen(my_vendor.name) + 1;
277 /* Set up the database record's data */
278 data.data = &my_vendor;
279 data.size = sizeof(my_vendor);
282 * Note that given the way we built our struct, there are extra
283 * bytes in it. Essentially we're using fixed-width fields with
284 * the unused portion of some fields padded with zeros. This
285 * is the easiest thing to do, but it does result in a bloated
286 * database. Look at load_inventory_data() for an example of how
290 /* Put the data into the database.
291 * Omitting error handling for clarity.
293 my_stock.vendor_dbp->put(my_stock.vendor_dbp, 0,
294 &key, &data, 0);
295 } /* end vendors database while loop */
297 /* Close the vendor.txt file */
302 Finally, we need to write the
303 <code class="function">load_inventory_database()</code> function. We made this function a
304 bit more complicated than is necessary by avoiding the use of a
305 structure to manage the data. Instead, we manually pack all our inventory
306 data into a single block of memory, and store that data in the
310 While this complicates our code somewhat, this approach allows us to
311 use the smallest amount of space possible for the data that we want to
312 store. The result is that our cache can be smaller than it might
313 otherwise be and our database will take less space on disk than if we used
314 a structure with fixed-length fields.
317 For a trivial dataset such as what we use for these examples, these
318 resource savings are negligible. But if we were storing hundreds of
319 millions of records, then the cost savings may become significant.
322 Before we actually implement our inventory loading function, it is useful
323 to create a simple utility function that copies a character array into a
324 buffer at a designated offset:
327 <pre class="programlisting">/*
328 * Simple little convenience function that takes a buffer, a string,
329 * and an offset and copies that string into the buffer at the
330 * appropriate location. Used to ensure that all our strings
331 * are contained in a single contiguous chunk of memory.
334 pack_string(char *buffer, char *string, int start_pos)
336 int string_size = strlen(string) + 1;
338 memcpy(buffer+start_pos, string, string_size);
340 return(start_pos + string_size);
343 That done, we can now load the inventory database:
346 <pre class="programlisting">/*
347 * Loads the contents of the inventory.txt file into
351 load_inventory_database(STOCK_DBS my_stock, char *inventory_file)
360 * Rather than lining everything up nicely in a struct, we're being
361 * deliberately a bit sloppy here. This function illustrates how to
362 * store mixed data that might be obtained from various locations
363 * in your application.
367 char category[MAXFIELD], name[MAXFIELD];
368 char vendor[MAXFIELD], sku[MAXFIELD];
370 /* Load the inventory database */
371 ifp = fopen(inventory_file, "r");
373 fprintf(stderr, "Error opening file '%s'\n", inventory_file);
377 /* Get our buffer. MAXDATABUF is some suitably large number */
378 databuf = malloc(MAXDATABUF);
381 * Read the inventory.txt file line by line, saving each line off to
382 * the database as we go.
384 while(fgets(buf, MAXLINE, ifp) != NULL) {
386 * Scan the line into the appropriate buffers and variables.
387 * Convenient, but not particularly safe. In a real
388 * program, there would be a lot more defensive code here.
391 "%20[^#]#%20[^#]#%f#%i#%20[^#]#%20[^\n]",
392 name, sku, &price, &quantity, category, vendor);
395 * Now pack it into a single contiguous memory location for
398 memset(databuf, 0, MAXDATABUF);
403 * We first store the fixed-length elements. This makes our code
404 * to retrieve this data from the database a little bit easier.
407 /* First discover how long the data element is. */
408 dataLen = sizeof(float);
409 /* Then copy it to our buffer */
410 memcpy(databuf, &price, dataLen);
412 * Then figure out how much data is actually in our buffer.
413 * We repeat this pattern for all the data we want to store.
417 /* Rinse, lather, repeat. */
418 dataLen = sizeof(int);
419 memcpy(databuf + bufLen, &quantity, dataLen);
422 bufLen = pack_string(databuf, name, bufLen);
423 bufLen = pack_string(databuf, sku, bufLen);
424 bufLen = pack_string(databuf, category, bufLen);
425 bufLen = pack_string(databuf, vendor, bufLen);
428 * Now actually save the contents of the buffer off
432 /* Zero out the DBTs */
433 memset(&key, 0, sizeof(DBT));
434 memset(&data, 0, sizeof(DBT));
437 * The key is the item's SKU. This is a unique value, so we need
438 * not support duplicates for this database.
441 key.size = strlen(sku) + 1;
443 /* The data is the information that we packed into databuf. */
447 /* Put the data into the database */
448 my_stock.vendor_dbp->put(my_stock.inventory_dbp, 0,
449 &key, &data, 0);
450 } /* end vendors database while loop */
460 In the next chapter we provide an example that shows how to read
461 the inventory and vendor databases.
465 <br class="example-break" />
467 <div class="navfooter">
469 <table width="100%" summary="Navigation footer">
471 <td width="40%" align="left"><a accesskey="p" href="cstructs.html">Prev</a> </td>
472 <td width="20%" align="center">
473 <a accesskey="u" href="DBEntry.html">Up</a>
475 <td width="40%" align="right"> <a accesskey="n" href="Cursors.html">Next</a></td>
478 <td width="40%" align="left" valign="top">Using C Structures with DB </td>
479 <td width="20%" align="center">
480 <a accesskey="h" href="index.html">Home</a>
482 <td width="40%" align="right" valign="top"> Chapter 4. Using Cursors</td>