New Features of Java SE 6: java db and JDBC 4.0

Source: Internet
Author: User
Tags java se
For a long time, since a large number of (or even almost all) Java applications rely on databases, it has been a hot topic for programmers to use the Java language to access databases efficiently, reliably, and concisely. The newly released Java SE 6 is also upgraded in this regard, providing programmers with many useful new features. Specifically, Java SE 6 has an embedded 100% database system written in Java. In addition, Java 6 began to support a series of new features and attributes of JDBC 4.0. In this way, Java SE is more easy to use and powerful in accessing persistent data.

Java db: databases in Java 6

Programmers who have installed JDK 6 may find that in addition to the traditional bin and JRE directories, JDK 6 adds a directory named dB. This is a new member of Java 6: java db. This is a pure Java-implemented, open-source database management system (DBMS), originated from the project Derby under the Apache Software Foundation (ASF. It is only 2 MB in size, which is a pocket-sized database compared to the database with frequent access to G. However, this does not prevent Derby from being fully functional and supports the features required by almost all database applications. What's even more valuable is that, relying on the strong community power of ASF, Derby is supported by large companies including IBM and sun and excellent programmers from around the world. It is no wonder that Sun chose to include its 10.2.2 version in JDK 6 as an embedded database. This seems to inject a brand new vitality into JDK: Java programmers no longer need to spend a lot of energy installing and configuring databases, so they can perform secure, easy-to-use, standard, and free database programming. In this chapter, we will first look at the world of java db to explore how to use it to compile programs with rich functions.

Hello, java db: derby in Embedded Mode

Now that we have an embedded database, let's start with a simple example (the code is listed in Listing 1) and try to use it. This program performs operations that most database applications may perform: Create a database named hellodb In the DBMS, and create a data table named hellotable; insert two pieces of data into the table. Then, query the data and print the result on the console. Finally, delete the table and database and release the resource.

Listing 1. hellojavadb code
Public class hellojavadb {
Public static void main (string [] ARGs ){
Try {// load the driver
Class. forname ("org. Apache. Derby. JDBC. embeddeddriver"). newinstance ();
System. Out. println ("load the embedded driver ");
Connection conn = NULL;
Properties props = new properties ();
Props. Put ("user", "user1"); props. Put ("password", "user1 ");
// Create and connect the database named hellodb
Conn = drivermanager. getconnection ("JDBC: Derby: hellodb; Create = true", props );
System. Out. println ("Create and connect to hellodb ");
Conn. setautocommit (false );

// Create a table and insert two records
Statement S = conn. createstatement ();
S.exe cute ("create table hellotable (name varchar (40), score INT )");
System. Out. println ("created table hellotable ");
S.exe cute ("insert into hellotable values ('ruth Cao ', 86 )");
S.exe cute ("insert into hellotable values ('flora Shi', 92 )");
// List the two records
Resultset rs = s.exe cutequery (
"Select name, score from hellotable order by score ");
System. Out. println ("name/T/tscore ");
While (Rs. Next ()){
Stringbuilder builder = new stringbuilder (Rs. getstring (1 ));
Builder. append ("/t ");
Builder. append (Rs. getint (2 ));
System. Out. println (builder. tostring ());
}
// Delete the table
S.exe cute ("Drop table hellotable ");
System. Out. println ("dropped table hellotable ");

Rs. Close ();
S. Close ();
System. Out. println ("Closed result set and statement ");
Conn. Commit ();
Conn. Close ();
System. Out. println ("committed transaction and closed connection ");

Try {// perform a clean shutdown
Drivermanager. getconnection ("JDBC: Derby:; shutdown = true ");
} Catch (sqlexception SE ){
System. Out. println ("database shut down normally ");
}
} Catch (throwable e ){
// Handle the exception
}
System. Out. println ("simpleapp finished ");
}
}

Then, run the following command in the command line (in this example, the Windows platform, of course, you can make a slight change to other systems:

Listing 2. Run the hellojavadb command
Java-CP.; % java_home %/DB/lib/Derby. Jar hellojavadb

The program will be executed as we expected. Figure 1 is part of the execution result:

Figure 1. Execution result of the hellojavadb Program

The above procedures are no different from those in the past. The difference is that we don't need to worry about DBMS configuration, because Derby has automatically created a directory named hellodb under the current directory to physically store data and logs. All you need to do is pay attention to the naming problem: in Embedded mode, the driver name should be org. Apache. Derby. JDBC. embeddeddriver; when creating a new database, you must add create = true after the Protocol. In addition, you can use the following code to shut down all databases and Derby engines:

Listing 3. disabling all databases and Derby Engines
Drivermanager. getconnection ("JDBC: Derby:; shutdown = true ");

If you only want to close a database, you can call:

Listing 4. Closing a database
Drivermanager. getconnection ("JDBC: Derby: hellodb; shutdown = true ");

In this way, the cost of maintaining and managing databases using the Derby embedded mode is close to zero. This is good news for those who want to concentrate on writing code. However, some people may wonder why most DBMS systems do not adopt the embedded mode? You may wish to do a small experiment. When we run the hellojavadb program in two command line windows at the same time. The result of one result is the same as that of the previous one, but the other has an error, as shown in figure 2.

Figure 2. Limitations of the embedded Mode

The cause of the error is actually very simple: when using the embedded mode, Derby itself does not run in an independent process, but runs in the same Java Virtual Machine (JVM) together with the application. Therefore, Derby becomes a part of the application just like other jar files used by the application. This makes it easy to understand why our example program runs smoothly by adding the Derby JAR file to the classpath. This also shows that only one JVM can start the database: two applications running in different JVM instances naturally cannot access the same database.

In view of the limitations mentioned above and the need for multiple connections from different JVMs to access a database, the next section will introduce another Derby mode: network server ).

Network Server Mode

As mentioned above, the network server mode is a more traditional Client/Server mode. We need to start a derby network server to process client requests, whether from the same JVM instance or from another machine on the network. In addition, the client uses the drda (Distributed Relational database architecture) Protocol to connect to the server. This is a database interaction standard advocated by the Open Group. Figure 3 shows the general structure of the mode.

As Derby developers strive to reduce the difference between the network server mode and the embedded mode, we only need to modify the program in Listing 1. As shown in listing 5, a new function and some string variables are added to hellojavadb. It is not hard to see that the new Code only changes some strings that are specifically pointed out in the previous section: the driver class is Org. apache. derby. JDBC. clientdriver, and the database connection protocol becomes JDBC: Derby: // localhost: 1527 /. This is a URL-like string. In fact, the connection format of the Derby network client is JDBC: Derby: // server [: Port]/databasename [; attributekey = value]. In this example, we use the simplest local machine as the server, and the port is Derby's default port 1527.

Figure 3. Derby network server mode Architecture

Listing 5. hellojavadb in network server mode
Public class hellojavadb {
Public static string driver = "org. Apache. Derby. JDBC. embeddeddriver ";
Public static string protocol = "JDBC: Derby :";

Public static void main (string [] ARGs ){
// Same as before
}
Private Static void parsearguments (string [] ARGs ){
If (ARGs. Length = 0 | args. length> 1 ){
Return;
}
If (ARGs [0]. inclusignorecase ("derbyclient ")){
Framework = "derbyclient ";
Driver = "org. Apache. Derby. JDBC. clientdriver ";
Protocol = "JDBC: Derby: // localhost: 1527 /";
}
}
}

Of course, it is not enough to have only clients. We also need to start the network server. The class that controls the network server in Derby is org. Apache. Derby. drda. networkservercontrol. Therefore, type the following command. If you want to know more about networkservercontrol options, you only need to remove the start parameter to see the help information. All Network Server implementations are included in derbynet. Jar by derby.

Listing 6. Start a network server
Java-CP.; "C:/program files/Java/jdk1.6.0/DB/lib/Derby. Jar ";
"C:/program files/Java/jdk1.6.0/DB/lib/derbynet. Jar"
Org. Apache. Derby. drda. networkservercontrol start

Correspondingly, the implementation of the network client is included in derbyclient. jar. Therefore, you only need to add the JAR file to the classpath, and the modified client can read data smoothly. Try again using two command line windows to connect to the database, and you will be able to get the correct result. If you no longer need a server, you can use the shutdown parameter of networkservercontrol to disable the server.

More

So far, this article introduces Java dB (Derby), a new member of Java SE 6, and how to use java db in the embedded mode and network server mode. Of course, this is just a short taste. More advanced options need to be found in Sun and Derby documents. At the end of this chapter, we will briefly introduce several java db gadgets to speed up development. They are all located in the org. Apache. Derby. Tools Package. You need to obtain information or test them during development.

Related Article

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.