What is the difference between JDBC and Jndi connection methods __java

Source: Internet
Author: User
Tags connection pooling jboss
DBC is a database intermediary agent in order to be a Java connection to the database of a protocol or a method, through the Jdbc-odbc method of database connection, is to connect one time to create the practice 1, by the database driver and protocol to form a method of connecting data, call the broker provided by the class package, to create a connection 2. Again by the connection to call 3 states. 3. Provided by the State to the operation of the database Jndi is a way of naming trees, the required classes are listed in the style of the directory, which need to be directly according to the name of the call, is a relatively fast clean thought and behavior. When you want to manipulate the database using the JDBC operation naming Service The Jndi Java Database Connectivity (JDBC) is a standard Java API that consists of a set of classes and interfaces that Java application developers use to access databases and execute SQL statements JNDI (Java Name Directory Interface), which is not just a database location, is a unique identifier for all resources managed by the current application server, including databases, Web pages, files, connection pooling, and so on.



Configuring Jndi Bindings

The data sources that are bound here are implemented as DBCP. You must first copy the database driver (here with the MySQL database) and the Jar packages required by DBCP to the Lib directory in the Jetty root directory. DBCP mainly requires the following 3 documents:
Commons-dbcp.jar
Commons-pool.jar
Commons-collections.jar

JDBC and Jndi differences

Connection conn = null;
try{
Class.forName ("Com.mysql.jdbc.Driver", True,thread.currentthread (). Getcontextclassloader ());
conn = Drivermanager.getconnection ("jdbc:mysql://mydbserver?user=***&password=****");
.....
Conn.close ();
}
catch (...) {...} finally{
if (conn!=null) {
try{
Conn.close ();
}
catch (...) {...}
}
}
The problems that exist.
1, the database server name mydbserver user name and password may need to modify, which triggers the JDBC URL repair to modify;
2, the database may use other products;
3, with the actual terminal increase, the original configuration of the connection pool parameters may need to be adjusted;

Solutions
Programmers don't have to care about database-level things, just need to know how to reference them
The Jndi appears.
Define the data source, which is the JDBC reference parameter, and set a name for the data source;
To access a database by referencing the data source through the data source name in the program;

Jndi Connection

Context Initctx = new InitialContext ();
Context Envctx = (context) initctx.lookup ("java:comp/env");
DataSource ds = (DataSource) envctx.lookup ("Jdbc/webtest");
conn = Ds.getconnection ();

JDBC Connection
Class.forName ("Com.mysql.jdbc.Driver", True,thread.currentthread (). Getcontextclassloader ());
conn = Drivermanager.getconnection ("Jdbc:mysql://localhost/mismain?user=root&autoreconnect=true");

As programmers develop, they know that they want to develop access to the MySQL database, then encode a reference to the MySQL JDBC driver class and connect to the database by using the appropriate JDBC URL.

Just like the following code:

Connection Conn=null;
Try ... {
Class.forName ("Com.mysql.jdbc.Driver", True, Thread.CurrentThread (). Getcontextclassloader ());
Conn=drivermanager.getconnection ("Jdbc:mysql://mydbserver?user=qingfeng&password=mingyue");
......
Conn.close ();
catch (Exception e) ... {
E.printstacktrace ();
Finally ... {
if (conn!=null) ... {
Try ... {
Conn.close ();
catch (SQLException e) ... {}
}
}


This is the traditional practice, but also the previous non-Java programmers (such as Delphi, VB, etc.) common practice. This is generally not a problem in a small-scale development process, as long as programmers are familiar with the Java language, understand JDBC technology, and MySQL, they can quickly develop the appropriate application.

Problems with no Jndi practices: 1. Database server name MyDBServer, username, and password may need to be changed, causing the JDBC URL to be modified; 2, the database may switch to another product, such as DB2 or Oracle instead, The JDBC driver package and class name are required to be modified; 3. As the actual use of terminals increases, the original configured connection pool parameters may need to be adjusted; 4 、......

Solution: Programmers should not be concerned about "what is the background of a specific database." What is the JDBC driver. What is the JDBC URL format. What is the user name and password to access the database. "And so on, programmers should write a program that doesn't have a reference to the JDBC driver, no server name, no user name or password--not even a database pool or connection management." Instead, these problems are given to the Java container for configuration and management, and the programmer only needs to refer to these configurations and management.

From this, there is a jndi.

After Jndi practice: First, configure the Jndi parameter in the Java container, define a data source, that is, the JDBC reference parameter, set a name for the data source, and then, in the program, refer to the data source through the data source name to access the background database.

The details are as follows (take JBoss for example):

1. Configure the data source
Under the D:\jboss420GA\docs\examples\jca folder of JBoss, there are many data source definition templates for different database references. Copy the Mysql-ds.xml files to the server you are using, such as D:\jboss420GA\server\default\deploy.
Modify the contents of the Mysql-ds.xml file so that it can access your MySQL database correctly through JDBC,
As follows:

Connection Conn=null;
Try ... {
Class.forName ("Com.mysql.jdbc.Driver", True, Thread.CurrentThread (). Getcontextclassloader ());
Conn=drivermanager.getconnection ("Jdbc:mysql://mydbserver?user=qingfeng&password=mingyue");
......
Conn.close ();
catch (Exception e) ... {
E.printstacktrace ();
Finally ... {
if (conn!=null) ... {
Try ... {
Conn.close ();
catch (SQLException e) ... {}
}
}
<?xml version= "1.0" encoding= "UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>MySqlDS</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/lw</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password>rootpassword</password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.mysqlexceptionsorter</ Exception-sorter-class-name>
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>

Here, we define a data source named Mysqlds, whose parameters include the JDBC URL, driver class name, username and password, and so on.

2. Referencing the data source in the program:

Connection conn=null;try ... {
Context Ctx=new InitialContext ();
Object datasourceref=ctx.lookup ("Java:mysqlds"); Reference data source DataSource ds= (DataSource) datasourceref; Conn=ds.getconnection ();
......
C.close ();
catch (Exception e) ... {
E.printstacktrace ();
Finally ... {
if (conn!=null) ... {
Try ... {
Conn.close ();
catch (SQLException e) ... { }
}
}

The amount of programming code that uses JDBC directly or through a Jndi reference data source is almost the same, but now the program does not have to worry about the specific JDBC parameters.

After the system is deployed, if the related parameters of the database change, only need to reconfigure Mysql-ds.xml to modify the JDBC parameters, so long as the data source name is guaranteed unchanged, then the program source code need not be modified.

Thus, Jndi avoids the tight coupling between the program and the database, making the application easier to configure and easier to deploy.

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.