Application of Data Sources in JDBC (1)
Introduction
As we all know, JDBC (Java database connection) is an important part of Java 2 Enterprise Edition. It is based on the SQL Layer
API. By embedding SQL statements into JDBC interfaces, you can use Java Program Execute almost all
Database Operations. JDBC only provides interfaces. The database designer is required to implement specific classes. By generating this
Some interface instances, even for different databases, Java programs can correctly Execute SQL calls. So
Programmers do not have to focus on how to send SQL commands to the database, because programmers need to understand and use
Only JDBC interfaces are used. In rare cases, classes for specific databases are used.
Use Oracle's extended API.
In the JDBC program, the first thing to do is to connect to the database. In the example program, we use or
The JDBC package of acle8i. To connect to a database, follow these steps:
1. register the database driver ). You can call the Regis of the Java. SQL. drivermanager class
The terdriver method explicitly registers the driver. You can also implicitly register the driver by loading the database Driver Class.
. For example, we want to register with a virtual machine // explicitly register
Drivermanager. registerdriver (New Oracle. JDBC. Driver. // implicit Registration
Class. forname ("oracle. JDBC. Driver.
How to automatically register a database driver loaded by the classloader of a VM exceeds
The scope of the article is not discussed in detail here.
2. Establish a connection. Call the getconnection () method of the Java. SQL. drivermanager class to establish
Database connection. The getconnection () method returns a connection object. Note that getco
The nnection () method automatically selects the most appropriate driver from the database driver registry.
3. Allow automatic update (autocommit) after the connection is established ). The ser that calls the java. SQL. connection interface
The autocommit () method can be used 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 is
Net8 keyword-Value Pair format. Of course, the common format can also be used. The database is installed in
The protocol used on the server is TCP, the port used is 1521, the database Sid is chidb, and
The database driver is import java. SQL .*;
// Initialization constant
Private Static string url =
"Jdbcracle: thin: @ (description = (address = (host = Chicago)" +
"(Protocol = TCP) (Port = 1521) (CONNECT_DATA = (SID = chidb )))";
// You can also set the URL to "jdbcracle: thin: @ Chicago: 1521: chidb"
Private Static string username = "guest ";
Private Static string Password = "guest ";
Try
{
// Register the database
Class. forname ("Oracle. JDBC. Driver. // 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. First
Is a security issue, because the program Code Contains the user name and password. If you can get bytecode, you can
Use the decompilation tool to obtain the user name and password. The second is code portability. If you want to connect
The Library name or user name has changed. The programmer needs to 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, it is not conducive
The development of the software itself. In some cases, organizations that provide data do not want data.
The username and password of the library are known to programmers who write programs. This raises a question: how to make Java
Sensitive information is hidden when a connection is established with a database.
Data Source and JNDI
Data sources are a concept introduced in JDBC 2.0. Javax. SQL. dataso is defined in the JDBC 2.0 extension package.
Urce interface to describe this concept. If you want to establish a database connection
You can obtain the database connection from the data source. In this way, you only need to provide a logical name
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 interfac
E. It can be understood as a Java name and a directory service interface. JNDI provides an application with a remote
Service mechanism. These services can be any enterprise service. For JDBC applications, JNDI provides the number
Database Connection Service. Of course, JNDI can also provide other services to the database, but this is beyond the scope of this article, here
Do not discuss it.
In fact, JNDI is not hard to understand. To put it simply, the name service provides an object such as a file, printer, or server.
Ing to a logical name. For example, the name service in the operating system maps the printer to an I/O end.
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
. The 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 the services provided by objects and objects by using logical names, so that programmers can avoid
Use the code associated with the organization that provides the object. For example, the data source in JNDI is used in the following example,
Programmers do not need to provide
The following describes the data source and the javax. SQL. datasource interface in detail. All created numbers are stored in the data source.
Database connection information. Just as you can find a file in the file system by specifying a file name
The data source name. You can find the corresponding database connection. The javax. SQL. datasource interface is defined as follows:
How to Implement the data source. Nine attributes are defined in this interface. Table 1 lists the descriptions of these attributes. As this article
Taking 8i as an example, the rolename attribute is not implemented in 8i, so this attribute is not described in the table.
Table 1: Standard Data Source attributes
Attribute name
Attribute name
Attribute data type description
Databasename string database name, that is, the database Sid.
The name of the datasourcename string data source interface implementation class.
Description string describes the data source.
The network protocol name used for network protocol string communication with the server. In 8i, this attribute is only used in O
Valid for CI drivers. The default protocol is TCP.
Password string User Logon password.
Portnumber int 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 programmers cannot
To obtain the login password, which ensures security to a certain extent. Note that all methods are
Is the synchronized method, which is used to ensure the thread-safe of the application ). If
This method does not affect the proper running of the program even if the data source instance changes.
In addition to the attributes and methods defined by Sun, 8i also provides its own data source attributes and methods. These methods and
Properties are implemented in Oracle. JDBC. Pool. datasource. Table 2 shows the 8i extended data source attributes:
Table 2:
Attribute name attribute data type description
The type of the JDBC driver used by drivertype string, including oci8, thin, and kprb.
URL: the URL of the string database connection.
Tnsentry string TNS entry name
In addition to the methods defined in the javax. SQL. datasource interface
, 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 ()
In addition, datasource implements the java. Io. serializable and javax. Naming. referenceable interfaces.
.
Independent use of data sources
In practice, you can register datasource to JNDI or use it independently. The following is a separate
Example of using datasource:
// Initialize the data source instance
Datasource ODS = new datasource ();
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 datasource:
If the server-side internal driver is used, drivertype is
The property 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:
Jdbcracle: thin: Guest/guest @ Chicago: 1521: chidb;
If the URL attribute is set, tnsentry, drivertype, portnumber, networkprotocol, Server
The name and databasename attributes are invalid.
If the tnsentry attribute, portnumber, and networkprotoc are set
The ol, servername, and databasename attributes are invalid.
If the OCI driver is used and the networkprotocol attribute is set to IPC
All other attributes are 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. datasource;
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 a datasource instance
Datasource ODS = new datasource ();
ODS. setdrivertype ("thin ");
ODS. setservername ("Chicago ");
ODS. setnetworkprotocol ("TCP ");
ODS. setdatabasename ("chidb ");
ODS. setportnumber (1521 );
ODS. setuser ("guest ");
ODS. setpassword ("guest ");
// Register the datasource 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 datasource instance from JNDI
System. Out. println ("doing a lookup with the logical name:" + ln );
Datasource ODS = (datasource) CTX. Lookup (LN );
System. Out. println ("successful lookup ");
// Obtain the database connection from the queried datasource 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;
Stmt = NULL;
}
}
The program first generates a context instance. The javax. Naming. Context interface defines the name service environment (n
Aming context) and the operations supported by the environment. The name service environment is actually mapped by the name and object.
Shot composition. The environment Factory (context factory) for initializing the name service environment in the program is com. Sun. JNDI.
Fscontext. reffscontextfactory (this class can be found in fscontext. jar, because fscontext.
Jar contains a non-standard API. You need to download
Fscontext1_2beta3.zip. You can find fscontext. jar in this file ). Environment Factory
The function is to generate an instance named service environment, which is defined by the javax. Naming. SPI. initialcontextfactory interface.
Environment factory how to 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 ja at registration
VAX. Naming. Context. BIND () method. The parameter is the registration name and registration object. After successful registration
A. Binding file is generated under the Directory, which records the name and object of the current name service environment.
To query an object in the name service environment, you need to call javax. Naming. Context. Lookup ()
And explicitly convert the queried object to the 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 application
You can use RMI or CORBA to register or query objects in the name service environment. For example, in a server-client structure
The application on the client only needs to know the logic name of the data source object in the server name service environment
You can use RMI to query the data source on the server and establish a connection to the database.
The question that was raised.