Introduction to the JE of Berkeley db

Source: Internet
Author: User
Tags error handling int size
Introduction to the JE of Berkeley db

Introduction to the JE of Berkeley db get JE Installation environment code

Brief Introduction

    Berkeley DB java Edition (JE) is a completely Java-written, suitable for managing a large amount of file databases. Je has the following advantages:
    1, can efficiently handle 1 to 1 million records, restricting JE Database is often the hardware system, rather than JE itself.
    2, multithreading support, je Use the method of timeout to deal with the problem between threads.
    3, the database uses the simple key/value corresponding form.
    4, support things.
    5, allow the creation of a two-level library. So we can easily use the first level key, level two key to access our data.
    6, support RAM buffer, this can reduce the frequent IO operation.
    7, support log.
    8, data backup and recovery.
    9, cursor support. 、
Get JE installation environment
    Je Download address: http://download.oracle.com/otn/berkeley-db/je-7.5.11.zip
    Unpack after the package, the je_home/lib/ The jar file in Je-.jar is added to your environment variable to use JE.
    related help documents can refer to je_home/docs/index.html
    related source code see Je_home/src/*.*
Code
Je operation class: Package je_test;
    Import Java.io.File;
    Import java.io.UnsupportedEncodingException;

    Import java.util.ArrayList;
    Import Com.sleepycat.je.Cursor;
    Import Com.sleepycat.je.CursorConfig;
    Import Com.sleepycat.je.Database;
    Import Com.sleepycat.je.DatabaseConfig;
    Import Com.sleepycat.je.DatabaseEntry;
    Import com.sleepycat.je.Environment;
    Import Com.sleepycat.je.EnvironmentConfig;
    Import com.sleepycat.je.LockConflictException;
    Import Com.sleepycat.je.LockMode;
    Import Com.sleepycat.je.OperationStatus;
    Import com.sleepycat.je.Transaction;

    Import Com.sleepycat.je.TransactionConfig;

        public class Berkeleydbutil {//Database environment private environment env = NULL;

        Databases private static database Frontierdatabase = NULL;

        Database name private static String dbname = "Frontier_database"; Public Berkeleydbutil (String homedirectory) {//1, creating Environmentconfig EnviRonmentconfig envconfig = new Environmentconfig ();
            Envconfig.settransactional (TRUE);

            Envconfig.setallowcreate (TRUE);

            2, using Environmentconfig configuration environment env = new Environment (new File (homedirectory), envconfig);
            3, create databaseconfig databaseconfig dbconfig = new Databaseconfig ();
    Dbconfig.settransactional (TRUE);

            Dbconfig.setallowcreate (TRUE);

        4, using environment and Databaseconfig Open the database frontierdatabase = Env.opendatabase (null, dbname, dbconfig); /** writes a record to the database and determines whether there can be duplicate data.
        Incoming key and value * If you can have duplicate data, use put () directly, and if you cannot have duplicate data, use Putnooverwrite ().
                */Public Boolean writetodatabase (string key, String value, Boolean Isoverwrite) {try { Set Key/value, note that databaseentry is used within the bytes array Databaseentry thekey = new Databaseentry (Key.getbytes ("UTF-8
                ")); Databaseentry thedata = new DatabAseentry (Value.getbytes ("UTF-8"));
                Operationstatus status = NULL;
                Transaction TXN = null;
                    try {//1, transaction configuration TransactionConfig txconfig = new TransactionConfig ();
                    Txconfig.setserializableisolation (TRUE);
                    TXN = Env.begintransaction (null, txconfig); 2. Write data if (isoverwrite) {status = Frontierdatabase.put (Txn, Thekey, Thedat
                    a);
                    else {status = Frontierdatabase.putnooverwrite (Txn, Thekey, thedata);
                    } txn.commit ();  if (status = = Operationstatus.success) {System.out.println ("write to database + dbname +": "+ key +", "+
                        Value);
                    return true; else if (status = = Operationstatus.keyexist) {System.out.println("to the database + dbname +" write: "+ key +", "+ Value +" failed, the value already exists);
                    return false;
                        else {System.out.println ("write to database + dbname +": "+ key +", "+ Value +" failed ");
                    return false;
                    } catch (Lockconflictexception lockconflict) {txn.abort ();
                    System.out.println ("to the database + dbname +" write: "+ key +", "+ Value +" appear lock exception);
                return false; (Exception e) {//Error handling SYSTEM.OUT.PRINTLN (write to database + dbname +): "
                + key + "," + Value + "error");
            return false; }/* * read data from database incoming key return value */public string readfromdatabase (string key)
                {try {databaseentry Thekey = new Databaseentry (key.getbytes ("UTF-8")); Databaseentry thedata = new DatabasEentry ();
                Transaction TXN = null; try {//1, configure transaction related information TransactionConfig txconfig = new TransactionConfig ()
                    ;
                    Txconfig.setserializableisolation (TRUE);
                    TXN = Env.begintransaction (null, txconfig);
                    2, read data operationstatus status = Frontierdatabase.get (Txn, Thekey, Thedata, Lockmode.default);
                    Txn.commit (); if (status = = Operationstatus.success) {//3, convert bytes to string byte[] Retdata
                        = Thedata.getdata ();
                        String value = new String (Retdata, "UTF-8");
                        System.out.println ("From the database" + dbname + "read:" + key + "," + value);
                    return value;
                        else {System.out.println ("No Record found for key" + key + "'.");
    Return "";                } catch (Lockconflictexception lockconflict) {txn.abort ();
                    System.out.println ("From the database" + dbname + "read:" + key + "appear lock exception");
                Return "";
                } catch (Unsupportedencodingexception e) {e.printstacktrace ();
            Return "";
            * * * traverse all records in the database, return list/public arraylist<string> Geteveryitem () { TODO auto-generated Method Stub System.out.println ("=========== Traverse database + dbname +" in all data =======
            ===");
            Cursor mycursor = null;
            arraylist<string> resultlist = new arraylist<string> ();
            Transaction TXN = null;
                try {txn = this.env.beginTransaction (null, NULL);
                Cursorconfig cc = new Cursorconfig ();
                Cc.setreadcommitted (TRUE);
    if (mycursor = null)            MyCursor = Frontierdatabase.opencursor (TXN, CC);
                Databaseentry Foundkey = new Databaseentry ();
                Databaseentry founddata = new Databaseentry (); Use the Cursor.getprev method to traverse the cursor to fetch the data if (Mycursor.getfirst (Foundkey, founddata, lockmode.default) = = Operationst ATUs.
                    SUCCESS) {String thekey = new String (Foundkey.getdata (), "UTF-8");
                    String thedata = new String (Founddata.getdata (), "UTF-8");
                    Resultlist.add (Thekey); System.out.println ("Key |
                    Data: "+ Thekey +" | "+ Thedata +" "); while (Mycursor.getnext (Foundkey, founddata, lockmode.default) = operationstatus.success) {Theke
                        y = new String (Foundkey.getdata (), "UTF-8");
                        Thedata = new String (Founddata.getdata (), "UTF-8");
                        Resultlist.add (Thekey); System.out.println ("Key | Data: "+ Thekey + "|" + Thedata + "");
                } mycursor.close ();
                Txn.commit ();
            return resultlist;
                catch (Unsupportedencodingexception e) {e.printstacktrace ();
            return null;
                catch (Exception e) {System.out.println ("Geteveryitem processing exception");
                Txn.abort ();
                if (mycursor!= null) {mycursor.close ();
            return null;
            }/* * Delete a record from the database based on the key value */public boolean deletefromdatabase (String key) {
            Boolean success = false;
            Long Sleepmillis = 0; for (int i = 0; i < 3 i++) {if (sleepmillis!= 0) {try {Thread.
                Sleep (Sleepmillis);
         catch (Interruptedexception e) {e.printstacktrace ();       } sleepmillis = 0;
            } Transaction txn = null; try {//1, using the Cursor.getprev method to traverse the cursor to get the data transactionconfig Txconfig = new TransactionConfig (
                );
                Txconfig.setserializableisolation (TRUE);
                TXN = Env.begintransaction (null, txconfig);
                Databaseentry Thekey;

                Thekey = new Databaseentry (key.getbytes ("UTF-8"));
                2. Delete data and submit operationstatus res = Frontierdatabase.delete (TXN, Thekey);
                Txn.commit ();
                    if (res = = operationstatus.success) {System.out.println ("Remove from database + dbname +": "+ Key");
                    Success = true;
                return success; else if (res = = Operationstatus.keyempty) {System.out.println ("not found in database + dbname +": "+ key +".)
                Cannot delete "); else {System.out.println ("delete exerciseFor failure, as "+ res.tostring ());
            return false;
                catch (Unsupportedencodingexception e) {e.printstacktrace ();
            return false;
                catch (Lockconflictexception lockconflict) {System.out.println ("delete operation failed, lockconflict exception occurred");
                Sleepmillis = 1000;
            Continue
                    finally {if (!success) {if (Txn!= null) {Txn.abort ();
        }} return false;
            public void Closedb () {if (frontierdatabase!= null) {frontierdatabase.close ();
            } if (env!= null) {env.close ();

    }} JE Test class: Package je_test; public class Berkeleydbutiltest {private Berkeleydbutil dbutil = new Berkeleydbutil ("/users/liuzhixiong/deskto  

 p/envhome/");       public static void Main (string[] args) {new Berkeleydbutiltest (). Testwritetodatabase ();
            String key = "2";
            String value = new Berkeleydbutiltest (). Testreadfromdatabase (key);
        System.out.println ("value=" + value); public void Testwritetodatabase () {for (int i = 0; i < i++) {Dbutil.wri  
            Tetodatabase (i+ "", "Student" +i, true); } public string Testreadfromdatabase (string key) {String value = Dbutil.readfromdata
            Base (key);
        return value;  
            public int Testgeteveryitem () {int size = Dbutil.geteveryitem (). Size ();
        return size;  
        public void Testdeletefromdatabase () {dbutil.deletefromdatabase ("4");  
        public void Cleanup () {dbutil.closedb ();  
 } 
    }

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.