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��8.��Database Records" />
11    <link rel="prev" href="DBEntry.html" title="Chapter��8.��Database Records" />
12    <link rel="next" href="bindAPI.html" title="Using the BIND APIs" />
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��8.��Database Records</th>
23          <td width="20%" align="right">��<a accesskey="n" href="bindAPI.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#databaseRead">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            <code class="methodname">Database.put()</code> 
87             
88             
89            and
90            <code class="methodname">Database.get()</code> 
91             
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��9.��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>You can use the following methods to put database records:</p>
126        <div class="itemizedlist">
127          <ul type="disc">
128            <li>
129              <p>
130                <code class="methodname">Database.put()</code>
131              </p>
132              <p>
133            Puts a database record into the database. If your database does not
134            support duplicate records, and if the provided key already exists in
135            the database, then the currently existing record is replaced with
136            the new data.
137          </p>
138            </li>
139            <li>
140              <p>
141                <code class="methodname">Database.putNoOverwrite()</code>
142              </p>
143              <p>
144            Disallows overwriting (replacing) an existing record in the
145            database. If the provided key already exists in the database, 
146            then this method returns 
147            <code class="literal">OperationStatus.KEYEXIST</code> even if
148            the database supports duplicates.
149          </p>
150            </li>
151            <li>
152              <p>
153                <code class="methodname">Database.putNoDupData()</code>
154              </p>
155              <p>
156            Puts a database record into the database. If the provided key
157            and data already exists in the database (that is, if you are
158            attempting to put a record that compares equally to an existing
159            record), then this returns
160            <code class="literal">OperationStatus.KEYEXIST</code>.
161          </p>
162            </li>
163          </ul>
164        </div>
165        <p>
166        When you put database records, you provide both the key and the data as
167        <code class="classname">DatabaseEntry</code> objects. This means you must
168        convert your key and data into a Java <code class="literal">byte</code> array. For
169        example:
170      </p>
171        <a id="java_dbt3"></a>
172        <pre class="programlisting">package db.GettingStarted;
173
174import com.sleepycat.db.DatabaseEntry;
175import com.sleepycat.db.Database;
176
177...
178
179// Database opens omitted for clarity.
180// Databases must NOT be opened read-only.
181
182String aKey = "myFirstKey";
183String aData = "myFirstData";
184
185try {
186    DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
187    DatabaseEntry theData = new DatabaseEntry(aData.getBytes("UTF-8"));
188    myDatabase.put(null, theKey, theData);
189} catch (Exception e) {
190    // Exception handling goes here
191} </pre>
192      </div>
193      <div class="sect2" lang="en" xml:lang="en">
194        <div class="titlepage">
195          <div>
196            <div>
197              <h3 class="title"><a id="databaseRead"></a>Getting Records from the Database</h3>
198            </div>
199          </div>
200        </div>
201        <p>
202        The <code class="classname">Database</code> class provides several
203        methods that you can use to retrieve database records. Note that if your
204        database supports duplicate records, then these methods will only ever
205        return the first record in a duplicate set. For this reason, if your
206        database supports duplicates, you should use a cursor to retrieve
207        records from it. Cursors are described in <a class="xref" href="Cursors.html" title="Chapter��9.��Using Cursors">Using Cursors</a>.
208      </p>
209        <p>
210          You can use either of the following methods to retrieve records from the database:
211      </p>
212        <div class="itemizedlist">
213          <ul type="disc">
214            <li>
215              <p>
216                <code class="methodname">Database.get()</code>
217              </p>
218              <p>Retrieves the record whose key matches the key provided to the
219          method. If no records exists that uses the provided key, then
220          <code class="literal">OperationStatus.NOTFOUND</code> is returned.</p>
221            </li>
222            <li>
223              <p>
224                <code class="methodname">Database.getSearchBoth()</code>
225              </p>
226              <p>Retrieve the record whose key matches both the key and the data
227          provided to the method. If no record exists that uses the provided
228          key and data, then <code class="literal">OperationStatus.NOTFOUND</code> is
229          returned.</p>
230            </li>
231          </ul>
232        </div>
233        <p>Both the key and data for a database record are returned as
234      byte arrays  in <code class="classname">DatabaseEntry</code> objects. These objects are
235      passed as parameter values to the <code class="methodname">Database.get()</code> method.
236      </p>
237        <p>In order to retrieve your data once <code class="classname">Database.get()</code>
238      has completed, you must retrieve the <code class="literal">byte</code> array stored 
239      in the <code class="classname">DatabaseEntry</code> and then convert that 
240      <code class="literal">byte</code> array back to the
241      appropriate datatype. For example:</p>
242        <a id="java_dbt4"></a>
243        <pre class="programlisting">package db.GettingStarted;
244      
245import com.sleepycat.db.DatabaseEntry;
246import com.sleepycat.db.Database;
247import com.sleepycat.db.LockMode;
248import com.sleepycat.db.OperationStatus;
249
250...
251
252Database myDatabase = null;
253// Database opens omitted for clarity.
254// Database may be opened read-only.  
255  
256String aKey = "myFirstKey";
257
258try {
259    // Create a pair of DatabaseEntry objects. theKey
260    // is used to perform the search. theData is used
261    // to store the data returned by the get() operation.
262    DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
263    DatabaseEntry theData = new DatabaseEntry();
264    
265    // Perform the get.
266    if (myDatabase.get(null, theKey, theData, LockMode.DEFAULT) ==
267        OperationStatus.SUCCESS) {
268
269        // Recreate the data String.
270        byte[] retData = theData.getData();
271        String foundData = new String(retData, "UTF-8");
272        System.out.println("For key: '" + aKey + "' found data: '" + 
273                            foundData + "'.");
274    } else {
275        System.out.println("No record found for key '" + aKey + "'.");
276    } 
277} catch (Exception e) {
278    // Exception handling goes here
279}</pre>
280      </div>
281      <div class="sect2" lang="en" xml:lang="en">
282        <div class="titlepage">
283          <div>
284            <div>
285              <h3 class="title"><a id="recordDelete"></a>Deleting Records</h3>
286            </div>
287          </div>
288        </div>
289        <p>
290
291        You can use the 
292            <code class="methodname">Database.delete()</code>
293            
294            
295        method to delete a record from the database. If your database supports
296        duplicate records, then all records associated with the provided key are
297        deleted. To delete just one record from a list of duplicates, use a
298        cursor. Cursors are described in <a class="xref" href="Cursors.html" title="Chapter��9.��Using Cursors">Using Cursors</a>.
299
300      </p>
301        <p>
302          You can also delete every record in the database by using
303              <code class="methodname">Environment.truncateDatabase().</code>
304              
305              
306        </p>
307        <p>For example:</p>
308        <a id="java_dbt5"></a>
309        <pre class="programlisting">package db.GettingStarted;
310
311import com.sleepycat.db.DatabaseEntry;
312import com.sleepycat.db.Database;
313
314...
315
316Database myDatabase = null;
317// Database opens omitted for clarity.
318// Database can NOT be opened read-only.  
319  
320try {
321    String aKey = "myFirstKey";
322    DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
323    
324    // Perform the deletion. All records that use this key are
325    // deleted.
326    myDatabase.delete(null, theKey); 
327} catch (Exception e) {
328    // Exception handling goes here
329}</pre>
330      </div>
331      <div class="sect2" lang="en" xml:lang="en">
332        <div class="titlepage">
333          <div>
334            <div>
335              <h3 class="title"><a id="datapersist"></a>Data Persistence</h3>
336            </div>
337          </div>
338        </div>
339        <p>
340            When you perform a database modification, your modification is made
341            in the in-memory cache.  This means that your data modifications
342            are not necessarily flushed to disk, and so your data may not appear
343            in the database after an application restart.
344        </p>
345        <p>
346            Note that as a normal part of closing a database, its cache is
347            written to disk. However, in the event of an application or system
348            failure, there is no guarantee that your databases will close
349            cleanly. In this event, it is possible for you to lose data. Under
350            extremely rare circumstances, it is also possible for you to
351            experience database corruption.
352        </p>
353        <p>
354            Therefore, if you care if your data is durable across system
355            failures, and to guard against the rare possibility of
356            database corruption, you should use transactions to protect your
357            database modifications. Every time you commit a transaction, DB
358            ensures that the data will not be lost due to application or 
359            system failure.  Transaction usage is described in the
360                
361
362                
363
364                <span>
365                <em class="citetitle">Berkeley DB Getting Started with Transaction Processing</em> guide.
366                </span>
367        </p>
368        <p>
369            If you do not want to use transactions, then the assumption is that
370            your data is of a nature that it need not exist the next time your
371            application starts. You may want this if, for example, you are using
372            DB to cache data relevant only to the current application
373            runtime.
374        </p>
375        <p>
376            If, however, you are not using transactions for some reason and you
377            still want some guarantee that your database modifications are
378            persistent, then you should periodically
379                <span>run environment syncs.</span>
380                
381                
382            Syncs cause any dirty entries in the in-memory cache and the
383            operating system's file cache to be written to disk. As
384            such, they are quite expensive and you should use them sparingly.
385        </p>
386        <p>
387            Remember that by default a sync is performed any time a non-transactional
388            database is closed cleanly. (You can override this behavior by
389            specifying 
390                 
391                <code class="literal">true</code> 
392            on the call to 
393                
394                
395                <span><code class="methodname">Database.close()</code>.)</span>
396            
397            That said, you can manually run a sync by calling
398            
399                
400                
401                <code class="methodname">Database.sync().</code>
402            
403        </p>
404        <div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
405          <h3 class="title">Note</h3>
406          <p>
407                If your application or system crashes and you are not using
408                transactions, then you should either discard and recreate your 
409                databases, or verify them. You can verify a database using
410                    
411                    
412                    <span>Database.verify().</span>
413                If your databases do not verify cleanly, use the 
414                <span class="command"><strong>db_dump</strong></span> command to salvage as much of the
415                database as is possible. Use either the <code class="literal">-R</code> or
416                <code class="literal">-r</code> command line options to control how
417                aggressive <span class="command"><strong>db_dump</strong></span> should be when salvaging
418                your databases.
419            </p>
420        </div>
421      </div>
422    </div>
423    <div class="navfooter">
424      <hr />
425      <table width="100%" summary="Navigation footer">
426        <tr>
427          <td width="40%" align="left"><a accesskey="p" href="DBEntry.html">Prev</a>��</td>
428          <td width="20%" align="center">
429            <a accesskey="u" href="DBEntry.html">Up</a>
430          </td>
431          <td width="40%" align="right">��<a accesskey="n" href="bindAPI.html">Next</a></td>
432        </tr>
433        <tr>
434          <td width="40%" align="left" valign="top">Chapter��8.��Database Records��</td>
435          <td width="20%" align="center">
436            <a accesskey="h" href="index.html">Home</a>
437          </td>
438          <td width="40%" align="right" valign="top">��Using the BIND APIs</td>
439        </tr>
440      </table>
441    </div>
442  </body>
443</html>
444