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">
4  <head>
5    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6    <title>Reading and Writing Database Records</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="DBEntry.html" title="Chapter 3. Database Records" />
12    <link rel="next" href="cstructs.html" title="Using C Structures with DB" />
13  </head>
14  <body>
15    <div class="navheader">
16      <table width="100%" summary="Navigation header">
17        <tr>
18          <th colspan="3" align="center">Reading and Writing Database Records</th>
19        </tr>
20        <tr>
21          <td width="20%" align="left"><a accesskey="p" href="DBEntry.html">Prev</a> </td>
22          <th width="60%" align="center">Chapter 3. Database Records</th>
23          <td width="20%" align="right"> <a accesskey="n" href="cstructs.html">Next</a></td>
24        </tr>
25      </table>
26      <hr />
27    </div>
28    <div class="sect1" lang="en" xml:lang="en">
29      <div class="titlepage">
30        <div>
31          <div>
32            <h2 class="title" style="clear: both"><a id="usingDbt"></a>Reading and Writing Database Records</h2>
33          </div>
34        </div>
35      </div>
36      <div class="toc">
37        <dl>
38          <dt>
39            <span class="sect2">
40              <a href="usingDbt.html#databaseWrite">Writing Records to the Database</a>
41            </span>
42          </dt>
43          <dt>
44            <span class="sect2">
45              <a href="usingDbt.html#CoreDatabaseRead">Getting Records from the Database</a>
46            </span>
47          </dt>
48          <dt>
49            <span class="sect2">
50              <a href="usingDbt.html#recordDelete">Deleting Records</a>
51            </span>
52          </dt>
53          <dt>
54            <span class="sect2">
55              <a href="usingDbt.html#datapersist">Data Persistence</a>
56            </span>
57          </dt>
58        </dl>
59      </div>
60      <p>
61        When reading and writing database records, be aware that there are some
62        slight differences in behavior depending on whether your database supports duplicate
63        records. Two or more database records are considered to be duplicates of 
64        one another if they share the same key. The collection of records
65        sharing the same key are called a <span class="emphasis"><em>duplicates set.</em></span>
66
67        <span>
68            In DB, a given key is stored only once for a single duplicates set.
69        </span> 
70    </p>
71      <p>
72        By default, DB databases do
73        not support duplicate records. Where duplicate records are supported,
74        cursors (see below) are <span>typically</span> used
75        to access all of the records in the duplicates set.
76    </p>
77      <p>
78        DB provides two basic mechanisms for the storage and retrieval of database
79        key/data pairs:
80    </p>
81      <div class="itemizedlist">
82        <ul type="disc">
83          <li>
84            <p>
85            The 
86             
87            <code class="methodname">DBT-&gt;put()</code> 
88             
89            and
90             
91            <code class="methodname">DBT-&gt;get()</code> 
92             
93            methods provide the easiest access for all non-duplicate records in the database. 
94            These methods are described in this section.
95        </p>
96          </li>
97          <li>
98            <p>Cursors provide several methods for putting and getting database
99        records. Cursors and their database access methods are described in
100        <a class="xref" href="Cursors.html" title="Chapter 4. Using Cursors">Using Cursors</a>.</p>
101          </li>
102        </ul>
103      </div>
104      <div class="sect2" lang="en" xml:lang="en">
105        <div class="titlepage">
106          <div>
107            <div>
108              <h3 class="title"><a id="databaseWrite"></a>Writing Records to the Database</h3>
109            </div>
110          </div>
111        </div>
112        <p>
113        Records are stored in the database using whatever organization is
114        required by the access method that you have selected. In some cases (such as
115        BTree), records are stored in a sort order that you may want to define
116        (see <a class="xref" href="btree.html#comparators" title="Setting Comparison Functions">Setting Comparison Functions</a> for more information). 
117      </p>
118        <p>
119        In any case, the mechanics of putting and getting database records do not
120        change once you have selected your access method, configured your
121        sorting routines (if any), and opened your database. From your
122        code's perspective, a simple database put and get is largely the
123        same no matter what access method you are using.
124      </p>
125        <p>
126          You use 
127            <code class="methodname">DB-&gt;put()</code>
128            
129        to put, or write, a database record. This method requires you to provide
130        the record's key and data in the form of a pair of
131            <span><code class="methodname">DBT</code> structures.</span>
132            
133        You can also provide one or more flags that control DB's behavior
134        for the database write.
135      </p>
136        <p>
137        Of the flags available to this method, <code class="literal">DB_NOOVERWRITE</code>
138        may be interesting to you. This flag disallows overwriting (replacing)
139        an existing record in the database. If the provided key already exists
140        in the database, then this method returns <code class="literal">DB_KEYEXIST</code> even if
141        the database supports duplicates.
142      </p>
143        <p>
144        For example:
145    </p>
146        <a id="c_dbt3"></a>
147        <pre class="programlisting">#include &lt;db.h&gt;
148#include &lt;string.h&gt;
149
150...
151
152char *description = "Grocery bill.";
153DBT key, data;
154DB *my_database;
155int ret;
156float money;
157
158/* Database open omitted for clarity */
159
160money = 122.45;
161
162/* Zero out the DBTs before using them. */
163memset(&amp;key, 0, sizeof(DBT));
164memset(&amp;data, 0, sizeof(DBT));
165
166key.data = &amp;money;
167key.size = sizeof(float);
168
169data.data = description;
170data.size = strlen(description) +1; 
171
172ret = my_database-&gt;put(my_database, NULL, &amp;key, &amp;data, DB_NOOVERWRITE);
173if (ret == DB_KEYEXIST) {
174    my_database-&gt;err(my_database, ret, 
175      "Put failed because key %f already exists", money);
176}</pre>
177      </div>
178      <div class="sect2" lang="en" xml:lang="en">
179        <div class="titlepage">
180          <div>
181            <div>
182              <h3 class="title"><a id="CoreDatabaseRead"></a>Getting Records from the Database</h3>
183            </div>
184          </div>
185        </div>
186        <p>
187        You can use the
188            <code class="methodname">DB-&gt;get()</code>
189            
190        method to retrieve database records. Note that if your 
191        database supports duplicate records, then by default this method will only
192        return the first record in a duplicate set. For this reason, if your
193        database supports duplicates, the common solution is to use a cursor to retrieve
194        records from it. Cursors are described in <a class="xref" href="Cursors.html" title="Chapter 4. Using Cursors">Using Cursors</a>.
195      </p>
196        <p>
197        (You can also retrieve a set of duplicate records using a bulk get. 
198        To do this, you use the <code class="literal">DB_MULTIPLE</code> flag on the 
199        call to 
200            <span><code class="methodname">DB-&gt;get()</code>.</span>
201            
202        
203        For more information, see the DB Programmer's Reference Guide).
204      </p>
205        <p>
206          By default, 
207            <code class="methodname">DB-&gt;get()</code>
208            
209        returns the first record found whose key matches the key 
210        provide on the call to this method. If your database supports 
211        duplicate records, you can change this behavior slightly by supplying
212        the <code class="literal">DB_GET_BOTH</code> flag. This flag causes
213            <code class="methodname">DB-&gt;get()</code>
214            
215        to return the first record that matches the provided key and data.
216      </p>
217        <p>
218          If the specified key and/or data does not exist in the database, this
219        method returns <code class="literal">DB_NOTFOUND</code>.
220      </p>
221        <a id="c_dbt4"></a>
222        <pre class="programlisting">#include &lt;db.h&gt;
223#include &lt;string.h&gt;
224
225...
226
227DBT key, data;
228DB *my_database;
229float money;
230char description[DESCRIPTION_SIZE + 1];
231
232/* Database open omitted for clarity */
233
234money = 122.45;
235
236/* Zero out the DBTs before using them. */
237memset(&amp;key, 0, sizeof(DBT));
238memset(&amp;data, 0, sizeof(DBT));
239
240key.data = &amp;money;
241key.size = sizeof(float);
242
243data.data = description;
244data.ulen = DESCRIPTION_SIZE + 1;
245data.flags = DB_DBT_USERMEM;
246my_database-&gt;get(my_database, NULL, &amp;key, &amp;data, 0);
247
248/* 
249 * Description is set into the memory that we supplied.
250 */ </pre>
251        <p>
252        Note that in this example, the 
253            <code class="literal">data.size</code>
254        field would be automatically set to the size of the retrieved data.
255    </p>
256      </div>
257      <div class="sect2" lang="en" xml:lang="en">
258        <div class="titlepage">
259          <div>
260            <div>
261              <h3 class="title"><a id="recordDelete"></a>Deleting Records</h3>
262            </div>
263          </div>
264        </div>
265        <p>
266
267        You can use the 
268            
269            <code class="methodname">DB-&gt;del()</code>
270            
271        method to delete a record from the database. If your database supports
272        duplicate records, then all records associated with the provided key are
273        deleted. To delete just one record from a list of duplicates, use a
274        cursor. Cursors are described in <a class="xref" href="Cursors.html" title="Chapter 4. Using Cursors">Using Cursors</a>.
275
276      </p>
277        <p>
278          You can also delete every record in the database by using
279              
280              <code class="methodname">DB-&gt;truncate().</code>
281              
282        </p>
283        <p>For example:</p>
284        <a id="c_dbt5"></a>
285        <pre class="programlisting">#include &lt;db.h&gt;
286#include &lt;string.h&gt;
287
288...
289
290DBT key;
291DB *my_database;
292float money = 122.45;
293
294/* Database open omitted for clarity */
295
296/* Zero out the DBTs before using them. */
297memset(&amp;key, 0, sizeof(DBT));
298
299key.data = &amp;money;
300key.size = sizeof(float);
301
302my_database-&gt;del(my_database, NULL, &amp;key, 0);</pre>
303      </div>
304      <div class="sect2" lang="en" xml:lang="en">
305        <div class="titlepage">
306          <div>
307            <div>
308              <h3 class="title"><a id="datapersist"></a>Data Persistence</h3>
309            </div>
310          </div>
311        </div>
312        <p>
313            When you perform a database modification, your modification is made
314            in the in-memory cache.  This means that your data modifications
315            are not necessarily flushed to disk, and so your data may not appear
316            in the database after an application restart.
317        </p>
318        <p>
319            Note that as a normal part of closing a database, its cache is
320            written to disk. However, in the event of an application or system
321            failure, there is no guarantee that your databases will close
322            cleanly. In this event, it is possible for you to lose data. Under
323            extremely rare circumstances, it is also possible for you to
324            experience database corruption.
325        </p>
326        <p>
327            Therefore, if you care if your data is durable across system
328            failures, and to guard against the rare possibility of
329            database corruption, you should use transactions to protect your
330            database modifications. Every time you commit a transaction, DB
331            ensures that the data will not be lost due to application or 
332            system failure.  Transaction usage is described in the
333                
334
335                
336
337                <span>
338                <em class="citetitle">Berkeley DB Getting Started with Transaction Processing</em> guide.
339                </span>
340        </p>
341        <p>
342            If you do not want to use transactions, then the assumption is that
343            your data is of a nature that it need not exist the next time your
344            application starts. You may want this if, for example, you are using
345            DB to cache data relevant only to the current application
346            runtime.
347        </p>
348        <p>
349            If, however, you are not using transactions for some reason and you
350            still want some guarantee that your database modifications are
351            persistent, then you should periodically
352                
353                <span>call <code class="methodname">DB-&gt;sync()</code>.</span>
354                
355            Syncs cause any dirty entries in the in-memory cache and the
356            operating system's file cache to be written to disk. As
357            such, they are quite expensive and you should use them sparingly.
358        </p>
359        <p>
360            Remember that by default a sync is performed any time a non-transactional
361            database is closed cleanly. (You can override this behavior by
362            specifying 
363                <code class="literal">DB_NOSYNC</code> 
364                 
365            on the call to 
366                <span><code class="methodname">DB-&gt;close()</code>.)</span>
367                
368                
369            
370            That said, you can manually run a sync by calling
371            
372                <code class="methodname">DB-&gt;sync().</code>
373                
374                
375            
376        </p>
377        <div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
378          <h3 class="title">Note</h3>
379          <p>
380                If your application or system crashes and you are not using
381                transactions, then you should either discard and recreate your 
382                databases, or verify them. You can verify a database using
383                    <span>DB-&gt;verify().</span>
384                    
385                    
386                If your databases do not verify cleanly, use the 
387                <span class="command"><strong>db_dump</strong></span> command to salvage as much of the
388                database as is possible. Use either the <code class="literal">-R</code> or
389                <code class="literal">-r</code> command line options to control how
390                aggressive <span class="command"><strong>db_dump</strong></span> should be when salvaging
391                your databases.
392            </p>
393        </div>
394      </div>
395    </div>
396    <div class="navfooter">
397      <hr />
398      <table width="100%" summary="Navigation footer">
399        <tr>
400          <td width="40%" align="left"><a accesskey="p" href="DBEntry.html">Prev</a> </td>
401          <td width="20%" align="center">
402            <a accesskey="u" href="DBEntry.html">Up</a>
403          </td>
404          <td width="40%" align="right"> <a accesskey="n" href="cstructs.html">Next</a></td>
405        </tr>
406        <tr>
407          <td width="40%" align="left" valign="top">Chapter 3. Database Records </td>
408          <td width="20%" align="center">
409            <a accesskey="h" href="index.html">Home</a>
410          </td>
411          <td width="40%" align="right" valign="top"> Using C Structures with DB</td>
412        </tr>
413      </table>
414    </div>
415  </body>
416</html>
417