Application of embedded database in Java

xiaoxiao2021-03-06  41

Application of embedded database in Java

content:

I. Berkeley DB II. SQLite Reference About the author

There is also a Java area:

Teaching tools and product code and components all articles practical skills

The embedded database does not have to be installed, the size is small, and the speed is very fast. In many cases, it can replace the current popular mysql, SQLServer and other large and medium-sized databases. This article describes two embedded database products: Berkeley DB and SQLite, and focus on their interfaces between Java. Usually we use a variety of database products to implement storage, search and other functions of data, such as Oracle, SQL Server, MySQL, and more. In addition to providing basic queries, deletion, addition, these products also provide a lot of advanced features such as triggers, stored procedures, data backup recovery, full-text search functions, and more. But in fact, many applications only use the basic characteristics of these database products. And in some small applications, or some special occasions, such as desktop programs, these database products are significantly bloated. In these cases, the advantages of embedded databases are particularly obvious. The embedded database does not have to run a database engine that is run independently, which is the access to the data directly to the corresponding API to implement the access operation of the data. More straightforward, embedded database is a data file with basic database features. The difference between the embedded database and other database products is that the former is a program driver, and the latter is an engine response. One important feature of embedded database is that their volume is very small, and the compiled product is only dozens of K. This not only has a good choice for the data storage scheme of the desktop program, but also allows them to be applied to some mobile devices. At the same time, many embedded databases are also superior to other databases in performance, so the figure of embedded databases is also common in high performance applications. The following describes the embedded database, Berkeley DB, and SQLite, two open source. At the same time, focus on how to apply Java to connect these two embedded databases. I. Berkeley DB 1. Introduction Berkeley DB is a robust, high-speed industrial-grade embedded database product, you can find this embedded company on its official homepage (see Reference Link 1) database. A very important feature of Berkeley DB is that high speed storage. In the case of high flow, high merging, Berkeley DB is more excellent than non-embedded databases. So in some technical implementations, Berkeley DB is used as an intermediate data buffer layer of a large relational database, which is used to quickly save data, which may be imported into large databases in an appropriate time, thereby applying larger databases provided by large databases. Features. Although Berkeley DB is an open source product, it is not free for some of the commercial applications, but it is quite expensive. These business conditions exclude open source, do not issue distributed versions, and so on. For example, if your program is open source or just applied to a single website, in this case, Berkeley DB is free. 2. Getting the Java and Berkeley DB interface Berkeley DB current version is 4.1.25, with a Java interface. The downloaded compression package contains the source code and compile profiles of the C and Java languages. In the Windows platform, you can compile with MS Visual C 6.0 or MS VC.NET. The operation compiled with VC6 is described below: Open the VC engineering file in the source code build_win32 path, then select the DB_JAVA WIN32 Release compile option in the build menu. Specify the position of the header file when specifying JAVA localization interfaces such as JNI.h in the Tools menu option option of the VC.

You will find these headers in the JDK's include path, such as the joined path, may be like this: C: /jdk1.4/include and c: /jdk1.4/include/win32. Finally, in the Tools menu, the Options option also sets the execution path of Javaac.exe and Jar.exe, which makes the VC development environment can also call the Java compiler to complete compilation and packaging of Java interface classes in the VC environment. . After compiling, find db.jar, libdb41.dll, libdb_java41.dll in the file under the Release path, which consists of the Java interface package of Berkeley DB. 3. Applying Java and Berkeley DB interface Berkeley DB is not a relational database. You cannot apply a standard SQL statement to the database operation, to call a dedicated API implementation for its operation. These APIs provide query, insert, delete and other functions. For example, com.sleepycat.db.db class represents a database object. The PUT () method of the DB class is completed, and the get () method completes the function of reading the data. com.sleepycat.db.dbc is the cursor class of Berkeley DB, providing the function of traversing database records. Berkeley DB has a key value and a corresponding data value, and the key value and data must be an object of the class com.sleepycat.db.dbt or its subclass. DBT provides some ways to save the BYTE array or Object object to the DBT object. For example, SET_DATA (Byte []) or set_Object (Object) method in the DBT class. Note that the Java API naming method in Berkeley DB does not meet Java naming specifications, such as the set_data () method should be namedddata () method. Berkeley DB promises to provide a Java API that meets naming specifications in the next release. BERKELEY DB is stored directly in the data file directly, whether it is binary data or ASCII or Unicode and other encoded text. It is usually possible to use this feature and the concept of Java serialization. For example, a class public class accountinfo imports serializable {

//account information

Public String loginname;

Public String Password;

Public Boolean Auotlogin;

}

Only the definition of data items in this Accountinfo class. We can completely see this class as a definition in the table of the database. The serial binary data of the Accountinfo object can be saved with Berkeley DB to save the variable values ​​in this object. In operation, first call the SET_OBJECT (AccountInfo) method for the DBT, and then save this DBT object as a record to the table. Of course, we can also apply the way to inherit the DBT class to complete the saving of the data. The following simple code demonstrates how to store data into the database, and then browse all data with a cursor object.

// Note that the following procedures ignore some code for exception processing, write data initialization, etc., please edit it after proper modification

// Translate it

DB DBFILE = NULL;

/ / Generate DB object

DBFILE = New DB (NULL, 0);

// Open the database in BTREE, the library file is a MyData.db file under C: / Temp, the table name is Employee

// If the database does not exist, a new database is automatically generated.

DBFile.Open (NULL, "C: //temp//mydata.db", "Employee", DB.DB_BTREE,

DB.DB_CREATE, 0);

DBT Key = New DBT ();

DBT data = new dBt (); // Insert a data in the library file, if you already exist, print an error message

IF (DBFile.Put (NULL, Key, Data, DB.DB_APPpend) == db.db_keyexist) {

System.out.println ("Key Already EXISTS.");

}

// Turn off the data file

DBFILE.CLOSE (0);

/ / Re-open data file

DBFILE = New DB (NULL, 0);

DBFile.open (NULL, "C: //temp//mydata.db", "Employee", DB.DB_UNKNOWN,

0, 0644);

// Declare a database cursor DBC object Iterator

DBC Iterator = DBFILE.CURSOR (NULL, 0);

// Traverse the entire table

DBT Key = New DBT ();

While (Iterator.get (key, data, db.db_next) == 0)

{

System.out.println ("Reading");

}

// Close the cursor and data file

Iterator.close ();

DBFILE.CLOSE (0);

Do not set the path where libdb41.dll and libdb_java41.dll is set in the system environment variable path when running Berkeley DB. 4. Berkeley DB storage mode Berkeley DB provides four modes of storage data: Btree, Hash, Queue and Recno. When opening the database, you want to specify a storage mode, such as the parameter db.db_btree in the open () method in the previous example, is specified to open the database in BTREE mode. The BTREE mode is stored in the manner of sorted binary trees, and the HASH is stored in a linear hash table. Queue is used as a key value with a logical record number, and the fixed length data is a recorded value. The RECNO mode is also used as a key value with logical record numbers, but can save a record value of a long or growing. The logical record number mentioned here has two, variable, and fixed. Variable logical record numbers will change according to the increase in data records and delete. For example, there are 100 records in the database. If Article 80 records are deleted, then the logical record number recorded by Article 81 will automatically become 80, and the number 100 record logic record number will become 99. The fixed logical record number will not change regardless of how the database is operated. In Queue mode, logical record numbers can only be fixed. The RECNO mode can be selected by the configuration to be used as the key value. BTree mode can also be set, and variable logical record numbers are used as key values. These storage modes have advantages and disadvantages, and they should be selected according to the specific needs. When the key value does not want to use the logical record number, Btree or Hash is a must-have. BTREE mode is more suitable for continuous order, for example, when the key value is a time value, Btree is a good choice if there is a time value that is often read from a certain point in time. For random jump read, Hash mode is more appropriate. Queue and Recno are valued with record numbers, but the former is suitable for advanced first reading. Recno is usually the ideal storage mode for accessing a long text record. 5. The concept of Berkeley DB Environment Berkeley DB Environment provides a set of databases to provide parameter settings. More importantly, if you want to apply more advanced features, you must use an Environment feature, such as encrypting the saved data. 6. More Features In addition to the most basic insertion, query, delete function, Berkeley DB also provides features such as Transaction, Data Encryption, Synchronous Plock Control, Error Log, and Other. The picture below is a Berkeley DB function diagram. II. SQLite 1. Introduction to the developer of PHP will not feel unfamiliar with SQLite, because this lightweight embedded database product has been integrated in PHP5. SQLITE is more similar to the product of relational databases on the operation statement compared to Berkeley DB. Most standard SQL92 statements SQLITE can support. SQLite's copyright allows no restrictions, including commercial products. On the SQLite official master provided on the reference link, you can download the compiled SQLite program. But it is recommended to apply the CVS tool to download the latest version of SQLite source code. If you are using Make with Make under the * Nux platform. If there are two methods commonly used in the Windows platform, one is to compile the Linux emulation programs to the Windows platform, such as MAKE provided by MINGW or Cygwin. The second is to apply the MS VC platform compilation. The latter setting is slightly incapacitated, but the example of the MS VC6 project file provided on the reference link 5 can be imperative. When applied to this sample, it is important to note that since the SQLite source code is constantly updating, if there is some problems with the VC6 engineering file compile provided by the sample, the reader wants to adjust the compiled settings according to the specific situation.

2. Compiling third-party Java interface SQLite source code is C, and only interfaces of C and TCL languages ​​are provided on the official website. To apply Java interface, you can use the third party interface driver to find this Java interface program in the reference link. This interface provides two ways to connect SQLITE: First, use JNI technology to call SQLite's C language interface, which requires developers to have a certain understanding of the API of SQLite itself. In the second way, the interface program implements the JDBC interface of the Java standard specification so that developers can understand the JDBC. The process of compiling SQLite Java interfaces (including JNI and JDBC two interfaces) in the Windows system MS VC6 environment. If you are familiar with the settings compiled with C language, you can jump this. The first step first compiles the SQLITE source code into a lib static library file. The specific steps can directly apply the MS VC6 workspace files provided in the following reference link, which has a setting of compiling SQLITE to static libraries. After successful compilation, get the SQLIT.LIB file. The second step is to create a new VC DLL project, and then the Berkeley DB described above is the same as the setting of the Java localization interface, specifies the header file of JNI and other JNI compilation in the VC's Tools menu Options option. At the same time, you have to specify the SQLite.h header file location, this file is automatically generated when generating the SQLite static library, you can find it below the workspace directory where the SQLite.lib file is located, such as the added path is C: / SQLite / MSVC6. Then set the link to the SQLIT.lib library file in the Proview menu, and again in the Tools menu in the Tools menu, specify the search path of SQLite.lib. Note Some of the cases may be set to compile option Have_SQLITE_Compile to use some of the features of VM in SQLITE. SQLITE_JNI.DLL files can be obtained after successful compilation. The Java code in the third-party interface library contains JNI interfaces and multiple versions of JDBC interface programs, and selects the appropriate JDBC program based on your JRE version. The process of compiling these Java codes is not described here. The compiled Java class package plus the previous SQLite_jni.dll file, which constitutes the Java interface library of SQLite. When applying the Java language call JDBC or JNI interface, it is called the SQLite_jni.dll file by applying Java's localization technology. Complete the operation of the SQLite database. 3. Apply JNI Direct calls SQLITE Function The following code demonstrates how to use the JNI interface to operate SQLite. You can see that the exec () method of the Database class is the key to execute the SQL statement: Database DB = New Database ();

Try {

// Open the database

DB.Open ("c: //temp//mydata.slt", 0666);

db.interrupt ();

Db.busy_timeout (1000);

Db.busy_handler (null);

Db.exec ("Create Table Account (Name Varchar (10), Gale Boolean"

result);

Db.exec ("INSERT INTO Account Values", Result;

Db.exec ("Select * from account", result);

// Close the database

db.close ();

} catch (exception e) {

E.PrintStackTrace ();

}

4. Apply the JDBC to connect SQLITE with "SQLite.jdbcdriver" as the JDBC driver class name. Connecting the JDBC URL format is JDBC: SQLite: / path. The PATH here is the path to the SQLite database file, for example: JDBC: SQLite: // Dira / DIRB / DBFILE

JDBC: SQLITE: // Drive: / Dira / DIRB / DBFILE

JDBC: SQLite: // computername / ShareA / DIRB / DBFILE

Refer to the following application JDBC to connect the SQLite routine:

// Declare the JDBC driver

Class Clz = Class.Forname ("Sqlite.jdbdriver");

//Connect to the database

Connection conn = drivermanager.getConnection ("JDBC: SQLite: / C: /TEMP/E2.DB");

Statement Stmt = conn.createstatement ();

/ / Generate a Person table, including the name and age field

Stmt.execute ("CREATE TABLE PERSON (Name Varchar (100), Age Int");

// Insert data

Stmt.execute ("INSERT INTO PERSON VALUES (" 'Steve', 25) ");

// read the data with the SQL statement

Result = Stmt.executeQuery ("SELECT * from Person");

While (result.next ()) {

System.out.println (Result.getstring (1));

System.out.println (Result.GetinT (2));

}

When running a program, you should add the path to the Java.library.path in the java.library.path when running the program. For example, if sqlite_jni.dll is placed under the C: / SQLITENATIVE path, the command line of run class com.e2one.myClass will be like this: java -djava.library.path = c: / sqlitenative com.e2one.myclass. 5. SQLite's feature SQLite is a database of non-data type. Although when generating a table structure, declare the data type of each domain, but SQLite does not do any check. Developers should control the type of input to read data with their own program. Here there is an exception, that is, when the primary key is an integer value, it will produce an exception if a non-integer value is to be inserted. In addition, although it is not distinguished in insertion or reading data, different data types are different when compared. such as:

Create Table MyTable (A Integer, B Text);

INSERT INTO MyTable Values ​​(0,0);

Perform the following query:

Select count (*) from myTable where a == '00';

A record will be returned because the type of field A is integer, and the number 00 and 0 are equal. And the following query will not return records:

Select count (*) from myTable where b == '00';

转载请注明原文地址:https://www.9cbs.com/read-78153.html

New Post(0)