Data | The application of data source data source in JDBC It is well known that JDBC (Java database connection) is an important part of the JAVA2 Enterprise Edition. It is an API based on the SQL layer. By embedding SQL statements into the JDBC interface, users can perform almost all database operations through Java programs.
JDBC provides only interfaces, and the implementation of a specific class requires the designer of the database to complete it. By generating instances of these interfaces, Java programs can execute SQL calls correctly even for different databases. So for programmers, you don't have to focus on how to send SQL instructions to a database, because programmers need to understand and use only JDBC interfaces, and only in rare cases will use classes that target a particular database, such as a programmer who wants to use Oracle's extended 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 register the driver implicitly by loading the database driver class. For example, we would like to register oracle8i JDBC driver Explicit registration with the virtual machine:
There is no detailed discussion on how virtual machines automatically register a database driver loaded through the ClassLoader (ClassLoader), which is beyond the scope of this article.
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 should be noted that the getconnection () method automatically selects the most appropriate driver from the database driver registry.
3, after the establishment of the connection
Allow Automatic Updates (autocommit). The Serautocommit () method that invokes the Java.sql.Connection interface can set whether the database is updated immediately after the program sends an SQL instruction to the database. The following is a concrete example.
In this instance, the URL used as the getconnection () method parameter is in the 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 SID of the database is CHIDB, and the database driver used is the Oracle JDBC thin driver.
Import java.sql.*;
Initialize 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 ';p rivate static String
Password = "Guest";
Try
{
Registering a database
Class.forName ("Oracle.jdbc.driver.OracleDriver");
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 perspective of practical application, we can see that there are several problems in this way to connect to the database. The first is the security issue, because the program code contains the username and password, other people if you can get bytecode, you can use the Decompile tool to obtain the user name and password.
The second is the portability of code. If you want the database name or user name of the connection to change, the programmer needs to modify the source program and then send the modified program to the user. That is, the 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 the software itself.
It is also possible that, in some cases, the organization that provides the data does not want the database username and password to be known to programmers who write the program. This raises the question of how to hide sensitive information when establishing a connection between Java and the database.
The 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 expansion pack to describe this concept. If a user wishes to establish a database connection, it is possible to obtain the corresponding database connection 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. Here it is necessary to briefly introduce Jndi. The full name of Jndi is the Java naming and directory Interface, which can be understood as the 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 a database connection service. Of course Jndi can also provide other services to the database, but this is beyond the scope of this article, this is not discussed here.
In fact, Jndi is not difficult to understand. In simple terms, 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. Directory services, however, can be understood as an extension of the name service, which allows the items in the service to have their own attributes.
Also take the printer as an example, the printer can be a color printer, support double-sided printing, support network printing, support high-speed printing and so on. The properties of all 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, and so on.
Jndi enables an application to get the services provided by objects and objects by using a logical name, so that programmers can avoid using code that is associated with the organization that provides the object. For example, in the following example, a data source in Jndi is used, and the programmer does not need to provide the name of the oracle8i driver, so the code can be more portable.
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 a file in the file system by specifying the filename, you can find the appropriate database connection by providing the correct data source name.
The Javax.sql.DataSource interface defines how to implement a data source. Nine properties are defined in this interface. At the same time, Oracledatasource also implements the Java.io.Serializable and Javax.naming.Referenceable interfaces. Using a data source for your own use, you can register the Oracledatasource to Jndi, or you can use it separately.
Here is a separate example of using Oracledatasource:
Initializing a 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");
Get the 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 Oracledatasource: If you are using a server-side internal driver (Server-side internal driver), 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 a user login name and a user login password. For example:
JDBC:ORACLE:THIN:GUEST/GUEST@CHICAGO:1521:CHIDB;
If the URL attribute is set, Tnsentry, Drivertype, PortNumber, Networkprotocol, ServerName, and DatabaseName properties will be invalidated. In the absence of a URL attribute setting, if the Tnsentry property is set, the PortNumber, Networkprotocol, ServerName, and DatabaseName properties will fail.
If you use the OCI driver, and the Networkprotocol property is set to IPC, all other properties except user and password will be invalidated. Using a data source through Jndi in this section, you first give a real-world program and then use a 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.OracleDataSource;
Import javax.naming.*;
Import javax.naming.spi.*;
Import java.util.Hashtable;
public class Datasourcejndi
{
public static void Main
(String args []) throws SQLException
{
Initializes 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 Oracledatasource
Example 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 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 Oracledatasource from Jndi
Instance System.out.println
("Doing a lookup with the logical name
: "+ ln);
Oracledatasource ODS
= (Oracledatasource)
Ctx.lookup (LN);
SYSTEM.OUT.PRINTLN ("successful lookup");
Oracledatasource from query to
instance to get the database connection
Connection conn = Ods.getconnection ();
Perform database Operation GetUserName (conn);
Close connection conn.close ();
conn = null;
}
static void GetUserName
(Connection conn) throws SQLException
{
Generates 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 all addressbook tables while
(Rset.next ()) System.out.println
("Name is" + rset.getstring (1));
Close Rseultset instance rset.close ();
RSet = null;
Close Statement instance 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 actions that the environment supports. The name service environment is actually made up of the mappings between names and objects. The environment factory in which 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 standard APIs, users need to start from www.javasoft.c The Jndi area in the OM downloads a compressed file named Fscontext1_2beta3.zip, where Fscontext.jar can be found.
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", which means that the environment is stored in a JNDI directory on the local hard drive. Once the name service environment is initialized, the data source instance can be registered in 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.
After the registration is successful, a. binding file is generated in the Jndi directory, which records the name and object owned by the current name service environment. When you need to query an object in a Name service environment, you need to call the Javax.naming.Context.lookup () method and explicitly convert the queried object to the data source object.
The data source object is then used for database operations. In this case, both the program and the name Service environment are running on the same machine. In practical 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 only needs to know the logical name of the data source object in the server Name service environment, you can query the data source via RMI to the server, and then by establishing a connection to the database. This will solve the problem that was first raised in this article.
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.