Brief introduction
As we all know, JDBC (Java database connection) is an important part of Java 2 Enterprise Edition. It is a SQL-layer-based API. By embedding SQL statements in the JDBC interface approach, users can perform almost any database operation through a Java program. JDBC provides only interfaces, and the implementation of a specific class requires the designer of the database to complete. By generating instances of these interfaces, Java programs can execute SQL calls correctly, even for different databases. So for programmers, there is no need to focus on how to send SQL instructions to the database, because programmers need to understand and use only the JDBC interface, and only in rare cases will be used for specific database-oriented classes, such as programmers want to use Oracle's extension API.
In the JDBC program, the first thing to do is to implement a connection to the database. In the sample program, we are using the oracle8i JDBC package. Connecting to a database typically requires the following steps:
1. Register the database driver (driver). You can explicitly register the driver by calling the Registerdriver method of the Java.sql.DriverManager class, or you can implicitly register the driver by loading the database driver class. For example, we want to register with a virtual machine
|
Explicit sign-up
Drivermanager.registerdriver (new oracle.jdbc.driver.//implicit sign-up
Class.forName ("Oracle.jdbc.driver. |
about how virtual machines are automatically enrolled database drivers that are loaded through the ClassLoader (ClassLoader) are beyond the scope of this article and are not discussed in detail here.
2. Establish the connection. Call the Getconnection () method of the Java.sql.DriverManager class to establish a connection to the database. The getconnection () method returns a Connection object. It is important to note that the getconnection () method automatically selects the most appropriate driver from the database driver registry.
3. After the connection is established, Automatic Updates (autocommit) are allowed. Call the Serautocommit () method of the Java.sql.Connection interface to set whether the database is updated immediately after the program issues an SQL instruction to the database.
The following is a concrete example. In this instance, the URL that is used as the getconnection () method parameter is in NET8 keyword-value pair format. Of course, you can also use the normal format. The database is installed on a server named Chicago, the protocol used is the TCP protocol, the port used is 1521, the database SID is Chidb, and the database driver that is used is
|
import java.sql.*;
// Initialization constant
private static string url =
"jdbc:oracle:thin:@ (description= ( address= (Host=chicago) " +
" (protocol=tcp) (port=1521)) (Connect_data= (SID=CHIDB))) ";
// can also set the URL to "JDBC:ORACLE:THIN:@ CHICAGO:1521:CHIDB"
private static string username = "Guest";
private static string password = "Guest";
Try
{
// Registry database
Class.forName ("Oracle.jdbc.driver. Establish a connection
connection conn =
Drivermanager.getconnection (url, username, password);
Allow automatic update of
Conn.setautocommit (true);
}
catch (classnotfoundexception e )
{
E.printstacktrace ();
}
catch (sqlexception e)
{
E.printstacktrace ();
} |
From the point of view of practical application, we can see that there are several problems in connecting to the database in this way. The first is the security issue, because the program code contains the user name and password, if the other person can get bytecode, you can get the user name and password by the Anti-compilation tool. The second is the portability of the code. If the database name or user name you want to connect to has changed, the programmer needs to modify the source program and then send the modified program to the user. That is, software cannot exist independently from the database. This will not only greatly improve the cost of software, but also not conducive to the development of software itself. It is also possible that in some cases, the organization that provides the data does not want the user name and password of the database to be known to programmers who write programs. This raises the question of how to hide sensitive information when connecting between Java and the database.
DataSource (data source) and Jndi
The data source is a concept introduced in JDBC 2.0. The Javax.sql.DataSource interface is defined in the JDBC 2.0 expansion pack to describe this concept. If the user wants to establish a database connection, the database connection can be obtained from the data source by querying the data source in the Jndi service. This allows the user to provide only a logical name (logic name) rather than the specifics of the database login.
It is necessary to introduce Jndi briefly here. The full name of Jndi is Java naming and directory Interface, which can be understood as the Java name and directory service interface. Jndi provides the 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 is not discussed here.
In fact, Jndi is not difficult to understand. Simply put, the name service provides a mechanism for mapping entities such as files, printers, servers, and so on 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 the items in the service to have their own properties. Again, for example, the printer can be a color printer, support duplex printing, support network printing, support high-speed printing and so on. All of these printer properties can be stored in the directory service, and associated with the corresponding printer. Some common directory services include NIS,NIS+,LDAP and Novell's NDS.
Jndi enables applications to obtain the services provided by objects and objects by using logical names, thus allowing programmers to avoid using code that is associated with the body that provides the object. For example, in the following example, using a data source in Jndi, the programmer does not need to provide
The data source and Javax.sql.DataSource interface are described in detail below. All information that establishes a database connection is stored in the data source. Just as you can find files in the file system by specifying a file name, you can find the appropriate database connection by providing the correct data source name. The Javax.sql.DataSource interface defines how the data source is implemented. Nine properties are defined in the interface. Table One lists descriptions of these properties. Since this article takes 8i as an example, the RoleName attribute is not implemented in 8i, so this attribute is not described in the table.
Table I: Data Source standard properties
|
Property name |
Property data type |
Describe |
|
DatabaseName |
String |
The database name, which is the SID of the database. |
|
DataSourceName |
String |
The name of the data source interface implementation class. |
|
Description |
String |
A description of the data source. |
|
Networkprotocol |
String |
The name of the network protocol used for communication with the server. In 8i, this property is only valid when using the OCI driver, and the default protocol is the TCP protocol. |
|
Password |
String |
User login password. |
|
PortNumber |
Int |
The default value for the port used by the database server is 1521. |
|
ServerName |
String |
The database server name. |
|
User |
String |
The user login name. |
The following methods are defined in the Javax.sql.DataSource interface:
|
* 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 get all the information needed to establish the connection. It is important to note that the programmer is not allowed to obtain the login password, which is to some extent to ensure security. Another point to note is that all methods are synchronized methods, which are designed to ensure thread-safe application (Thread-safe). If the method is called, even if the data source instance changes, it does not affect the correct operation of the program.
In addition to implementing properties and methods defined by Sun, 8i also provides its own data source properties and methods. These methods and properties are implemented in Oracle.jdbc.pool.DataSource. The 8i extended data source properties are shown in table two:
Table II:
|
Property name |
Property data type |
Describe |
|
Drivertype |
String |
Types of JDBC drivers 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.DataSource, the following methods are 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, DataSource also implements the Java.io.Serializable and Javax.naming.Referenceable interfaces.
Using data sources independently
In practice, you can register DataSource to Jndi, or you can use it alone. Here is an example of using DataSource alone:
|
Initializing 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");
Get a database connection from the data source
Connection conn = Ods.getconnection ();
Data manipulation through a database connection
.................. |
There are a few things to note when using DataSource:
- If the server-side internal driver (Server-side internal driver) is used, the Drivertype property is set to KPRB and all other properties are invalidated.
- If you use the thin or OCI driver:
- The URL can include the user login name and user login password. For example:
Jdbc:oracle:thin:guest/[email Protected]:1521:chidb;
- If the URL attribute is set, Tnsentry, Drivertype, PortNumber, Networkprotocol, ServerName, and DatabaseName properties will be invalidated.
- Without setting the URL property, if the Tnsentry attribute is set, PortNumber, Networkprotocol, ServerName, and DatabaseName properties will be invalidated.
- If the OCI driver is used and the Networkprotocol property is set to IPC, all other properties except user and password will be invalidated.
Working with data sources through Jndi
In this section, we first give a practical program, and then use the program to 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 Datasourcejndi
{
public static void Main (String args [])
Throws SQLException
{
Initializing 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");
Registering the DataSource instance in 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
{
Querying DataSource instances from Jndi
System.out.println ("Doing a lookup with the logical name:" + ln);
DataSource ODS = (DataSource) ctx.lookup (LN);
SYSTEM.OUT.PRINTLN ("successful lookup");
Getting a database connection from a query to a DataSource instance
Connection conn = Ods.getconnection ();
Perform database operations
GETUSERNAME (conn);
Close 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.executequery ("Select NAME from AddressBook");
List the names of the AddressBook table owners
while (Rset.next ())
System.out.println ("Name is" + rset.getstring (1));
Close Rseultset Instances
Rset.close ();
RSet = null;
Close Statement Instances
Stmt.close ();
stmt = null;
}
} |
The program first generates a context instance. The Javax.naming.Context interface defines the name service environment (naming context) and the operations supported by the environment. A name service environment is actually composed of a name and a mutual mapping between objects. The environment factory where the name service environment is initialized in the program (context Factory) is com.sun.jndi.fscontext.RefFSContextFactory (this class can be found in Fscontext.jar because Fscontext.jar contains not the standard API that the user needs from www.javasoft.c The Jndi zone in the OM downloads a compressed file named Fscontext1_2beta3.zip that can be found in the file (Fscontext.jar). The role of the environment factory is to generate an instance of the name Service environment, which defines how the environment factory should initialize the name Service environment (Javax.naming.spi.InitialContextFactory). You also need to define the URL of the environment when initializing the name service environment. The program uses "File:jndi", that is, the environment is stored in the local hard disk JNDI directory.
Once the name service environment is initialized, the data source instance can be registered to the name Service environment. The Javax.naming.Context.bind () method is called when registering, and the parameter is the registered name and the registered object. Upon successful registration, a. Binding file is generated in the Jndi directory that records the names and objects owned by the current name service environment.
When you need to query an object in the Name service environment, you need to call the Javax.naming.Context.lookup () method and explicitly convert the queried object to a data source object. The data source object is then performed for database operations.
In this example, both the program and the name Service environment are running on the same computer. In real-world applications, programs can register or query objects through RMI or CORBA to the name service environment. For example, in a server-client structure, the application on the client needs only to know the logical name of the data source object in the server name service environment, it can query the data source through RMI to the server, and then by establishing a connection to the database. This will solve the problem at the beginning of this article.
Use data source "reprint" via Jndi