Analysis on the Application of Data Sources in JDBC

Source: Internet
Author: User
   Introduction

As we all know, JDBC (Java database connection) is an important part of Java 2 Enterprise Edition. It is an API Based on the SQL layer. By embedding SQL statements into JDBC interfaces, you can use Java programs to perform almost all database operations. JDBC only provides interfaces. The database designer is required to implement specific classes. By generating instances of these interfaces, Java programs can correctly Execute SQL calls even for different databases. Therefore, programmers do not have to pay attention to how to send SQL commands to databases, because programmers only need to understand and use JDBC interfaces, only in rare cases will classes targeting specific databases be used. For example, programmers want to use Oracle's extended APIs.

In the JDBC program, the first thing to do is to connect to the database. In the example program, we use the JDBC package of Oracle8i. To connect to a database, follow these steps:

1. register the database driver ). You can explicitly register the driver by calling the registerdriver method of the Java. SQL. drivermanager class, or implicitly register the driver by loading the database Driver Class. For example, we want to register the Oracle8i JDBC driver with the VM.

// Explicitly register
Drivermanager. registerdriver (New Oracle. JDBC. Driver. oracledriver ());
// Implicit Registration
Class. forname ("Oracle. JDBC. Driver. oracledriver ");

How to automatically register a database driver loaded by the classloader of a VM exceeds the scope discussed in this article.

2. Establish a connection. Call the getconnection () method of the Java. SQL. drivermanager class to establish a connection with the database. The getconnection () method returns a connection object. Note that the getconnection () method automatically selects the most suitable driver from the database driver registry.

3. Allow automatic update (autocommit) after the connection is established ). You can call the serautocommit () method of the Java. SQL. connection interface to set whether the database is updated immediately after the program sends an SQL command to the database.

The following is a specific instance. In this instance, the URL used as the getconnection () method parameter uses the net8 keyword-Value Pair format. Of course, the common format can also be used. The database is installed on the server named Chicago. The protocol used is TCP, the port used is 1521, the database Sid is chidb, and the database driver used is the oracle JDBC thin driver.

Import java. SQL .*;

// Initialization constant
Private Static string url =
"JDBC: oracle: thin: @ (description = (address = (host = Chicago)" +
"(Protocol = TCP) (Port = 1521) (CONNECT_DATA = (SID = chidb )))";
// You can also set the URL to "JDBC: oracle: thin: @ Chicago: 1521: chidb"
Private Static string username = "guest ";
Private Static string Password = "guest ";

Try
{
// Register the database
Class. forname ("Oracle. JDBC. Driver. oracledriver ");
// Establish a connection
Connection conn =
Drivermanager. getconnection (URL, username, password );
// Allow Automatic Updates
Conn. setautocommit (true );
}
Catch (classnotfoundexception E)
{
E. printstacktrace ();
}
Catch (sqlexception E)
{
E. printstacktrace ();
}

From the perspective of practical application, we can see that there are several problems in connecting to the database using this method. The first is security. Because the program code contains the user name and password, if others can get bytecode, they can get the user name and password through The Decompilation tool. The second is code portability. If you want to change the name or user name of the connected database, the programmer must modify the source program and then send the modified program to the user. That is to say, the software cannot exist independently from the database. This will not only greatly increase the cost of the software, but also not conducive to the development of the software itself. In some cases, organizations that provide data do not want the database user name and password to be known to programmers. This raises a question about how to hide sensitive information when establishing a connection between Java and the database.

  Data Source and JNDI

Data sources are a concept introduced in JDBC 2.0. The javax. SQL. datasource interface is defined in the JDBC 2.0 extension package to describe this concept. If you want to establish a database connection and query the data source in the JNDI service, you can obtain the corresponding database connection from the data source. In this way, you only need to provide a logic name, rather than the specific details of database login.

It is necessary to briefly introduce the JNDI here. The full name of JNDI is Java Naming and Directory Interface, which can be understood as Java name and directory service interface. JNDI provides an application with a mechanism for querying and using remote services. These services can be any enterprise service. For JDBC applications, JNDI provides the Database Connection Service. Of course, JNDI can also provide other services to the database, but this is beyond the scope of this article and will not be discussed here.

In fact, JNDI is not hard to understand. Simply put, the name service provides a mechanism to map objects such as files, printers, and servers to a logical name. For example, the name service in the operating system maps the printer to an I/O port. The directory service can be understood as an extension of the name service, which allows each item in the Service to have its own attributes. For example, a printer can be a color printer that supports dual-sided printing, network printing, and high-speed printing. All the attributes of these printers can be stored in the directory service and associated with the corresponding printer. Some common directory services include NIS, NIS +, LDAP, and Novell NDS.

JNDI allows applications to obtain services provided by objects and objects by using logical names, so that programmers can avoid using code associated with the institution that provides objects. For example, if the data source in JNDI is used in the following example, the programmer does not need to provide the name of the Oracle8i driver, so that the Code porting capability is stronger.

The following describes the data source and the javax. SQL. datasource interface in detail. All database connection information is stored in the data source. Just as you can find the file in the file system by specifying the file name, you can find the corresponding database connection by providing the correct data source name. The javax. SQL. datasource interface defines how data sources are implemented. Nine attributes are defined in this interface. Table 1 lists the descriptions of these attributes. This document uses Oracle8i as an example. The rolename attribute is not implemented in Oracle8i, so this attribute is not described in the table.

Table 1: Standard Data Source attributes

Attribute name Attribute Data Type Description
Databasename String The database name, that is, the SID of the database.
Datasourcename String Name of the data source interface implementation class.
Description String Description of the data source.
Networkprotocol String The name of the network protocol used to communicate with the server. In Oracle8i, this attribute is valid only when the OCI driver is used. The default protocol is TCP.
Password String User Logon password.
Portnumber Int The port used by the database server. The default value is 1521.
Servername String Database Server name.
User String User Login Name.

The javax. SQL. datasource interface defines the following methods:

* Public synchronized void setdatabasename (string dbname)
* Public synchronized string getdatabasename ()
* Public synchronized void setdatasourcename (string dsname)
* Public synchronized string getdatasourcename ()
* Public synchronized void setdescription (string DESC)
* Public synchronized string getdescription ()
* Public synchronized void setnetworkprotocol (string np)
* Public synchronized string getnetworkprotocol ()
* Public synchronized void setpassword (string PWD)
* Public synchronized void setportnumber (int pn)
* Public synchronized int getportnumber ()
* Public synchronized void setservername (string Sn)
* Public synchronized string getservername ()
* Public synchronized void setuser (string user)
* Public synchronized string getuser ()

With these methods, the programmer can obtain all the information required to establish a connection. It should be noted that the programmer cannot obtain the login password, which ensures security to a certain extent. Note that all methods are synchronized to ensure thread-safe ). If this method is called, the program runs correctly even if the data source instance changes.

In addition to the attributes and methods defined by Sun, Oracle8i also provides its own data source attributes and methods. These methods and attributes are implemented in Oracle. JDBC. Pool. oracledatasource. Table 2 shows the Extended Data Source attributes of Oracle8i:

Table 2:

Attribute name Attribute Data Type Description
Drivertype String Type of the oracle JDBC driver used, including oci8, thin, and kprb
URL String The URL of the database connection.
Tnsentry String TNS entry name

In addition to implementing the methods defined in the javax. SQL. datasource interface in Oracle. JDBC. Pool. oracledatasource, the following methods are also implemented:

* Public synchronized void setdrivertype (string DT)
* Public synchronized string getdrivertype ()
* Public synchronized void seturl (string URL)
* Public synchronized string geturl ()
* Public synchronized void settnsentryname (string TNS)
* Public synchronized string gettnsentryname ()

At the same time, oracledatasource implements the java. Io. serializable and javax. Naming. referenceable interfaces.

  Independent use of data sources

In practice, you can register oracledatasource to JNDI or use it independently. Here is an example of using oracledatasource separately:

// Initialize the data source instance
Oracledatasource ODS = new oracledatasource ();

ODS. setdrivertype ("thin ");
ODS. setservername ("Chicago ");
ODS. setnetworkprotocol ("TCP ");
ODS. setdatabasename ("chidb ");
ODS. setportnumber (1521 );
ODS. setuser ("guest ");
ODS. setpassword ("guest ");

// Obtain the database connection from the data source
Connection conn = ODS. getconnection ();
// Perform data operations through database connection
..................

Note the following when using oracledatasource:

If the server-side internal driver is used, the drivertype attribute is set to kprb, and all other attributes are invalid.

If thin or OCI driver is used:

The URL can contain the User Logon Name and user logon password. For example:

JDBC: oracle: thin: Guest/guest @ Chicago: 1521: chidb;

If the URL attribute is set, the tnsentry, drivertype, portnumber, networkprotocol, servername, and databasename attributes are invalid.

If the URL attribute is not set, the tnsentry attribute, portnumber, networkprotocol, servername, and databasename attributes are invalid.

If the OCI driver is used and the networkprotocol attribute is set to IPC, all other attributes except user and password will be invalid.

  Use Data sources through JNDI

In this section, we first provide an actual program, and then explain how to query the data source through JNDI.

Import java. SQL .*;
Import javax. SQL .*;
Import oracle. JDBC. Driver .*;
Import oracle. JDBC. Pool. oracledatasource;
Import javax. Naming .*;
Import javax. Naming. SPI .*;
Import java. util. hashtable;

Public class performancejndi
{
Public static void main (string ARGs [])
Throws sqlexception
{
// Initialize the name service environment
Context CTX = NULL;
Try
{
Hashtable Env = new hashtable (5 );
Env. Put (context. initial_context_factory,
"Com. Sun. JNDI. fscontext. reffscontextfactory ");
Env. Put (context. provider_url, "file: JNDI ");
CTX = new initialcontext (ENV );
}
Catch (namingexception ne)
{
Ne. printstacktrace ();
}

BIND (CTX, "JDBC/chidb ");
Lookup (CTX, "JDBC/chidb ");

}

Static void BIND (context CTX, string ln)
Throws namingexception, sqlexception
{
// Create an oracledatasource instance
Oracledatasource ODS = new oracledatasource ();

ODS. setdrivertype ("thin ");
ODS. setservername ("Chicago ");
ODS. setnetworkprotocol ("TCP ");
ODS. setdatabasename ("chidb ");
ODS. setportnumber (1521 );
ODS. setuser ("guest ");
ODS. setpassword ("guest ");

// Register the oracledatasource instance to JNDI
System. Out. println ("doing a bind with the logical name:" + ln );
CTX. BIND (LN, ODS );
System. Out. println ("successfully bound ");
}

Static void Lookup (context CTX, string ln)
Throws namingexception, sqlexception
{
// Query the oracledatasource instance from JNDI
System. Out. println ("doing a lookup with the logical name:" + ln );
Oracledatasource ODS = (oracledatasource) CTX. Lookup (LN );
System. Out. println ("successful lookup ");

// Obtain the database connection from the queried oracledatasource instance
Connection conn = ODS. getconnection ();
// Perform database operations
GetUserName (conn );
// Close the connection
Conn. Close ();
Conn = NULL;
}

Static void GetUserName (connection conn)
Throws sqlexception
{
// Generate a statement instance
Statement stmt = conn. createstatement ();

// Select the name column from the addressbook table
Resultset rset = stmt.exe cutequery ("Select name from addressbook ");

// List the names of all users in the addressbook table
While (rset. Next ())
System. Out. println ("name is" + rset. getstring (1 ));

// Disable the rseultset instance
Rset. Close ();
Rset = NULL;

// Close the statement instance
Stmt. Close ();
Stmt = NULL;
}
}

The program first generates a context instance. The javax. Naming. Context interface defines the naming context and the operations supported by the environment. The name service environment is actually composed of mappings between names and objects. Initialize the environment factory of the name service environment in the program (the compressed file of context encryption, in which you can find fscontext. Jar ). The environment factory is used to generate an instance named service environment. The javax. Naming. SPI. initialcontextfactory interface defines how the environment factory should initialize the name service environment. When initializing the name service environment, you also need to define the environment URL. The program uses "file: JNDI", that is, to save the environment to the JNDI directory of the local hard disk.

After the name service environment is initialized, you can register the data source instance to the name service environment. Call the javax. Naming. Context. BIND () method during registration. The parameter is the registration name and the registration object. After successful registration, A. Binding file is generated under the JNDI Directory, which records the name and object of the current name service environment.

To query an object in the name service environment, call the javax. Naming. Context. Lookup () method and explicitly convert the queried object to a data source object. Then perform database operations through the data source object.

In this example, the program and name service environment run on the same computer. In actual applications, the program can register or query objects with the name service environment through RMI or CORBA. For example, in a server-client structure, the application on the client only needs to know the logical name of the data source object in the server name service environment, and you can query the data source from the server through RMI, then, establish a connection with the database. this will solve the problems raised at the beginning of this 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.