You are on page 1of 10

Contact Us

Search

Java Performance Best Practices for Profiling and Finding Java Application Issues. Offers.Compuware.com
Data Architect Buena Park, CA Work here -- love your job. dice.com/dntg
Online Java Training Placement oriented training by experts, Attend Free Demo Now www.h2kinfosys.com

Java – Choose best Database connectivity with web application Follow Me


Every w eb programmer thinks about the database connectivity before starting about
application. Good database connectivity can increase the performance of the w eb follow EasyWayServer on Twitter
application. We are explaining about different types of java database connectivity to
choose among the best. We have number of reason to choose different w ay of doing Like 17 likes. Sign Up to see what your friends like.
connectivity w ith database.

1. Simple JSP database connectivity Share Share with Facebook


2. JavaBean database connectivity
3. web.xml and Servlet database connectivity
4. Properties file database connectivity
Advertise here
5. XML file database connectivity
6. C onnection pooling java database connectivity

1. Simple JSP database connectivity

This is first most commonly used database connectivity by entry level java applications. We have
to w rite our code in JSP file and open connection in same file. Advance JSP database connection
can include a connection JSP file in all related JSP file w here database connection is required.

<%@ page language="java" import="java.sql.*"%>


<%
Connection conn = null;

Class.forName("com.mysql.jdbc.Driver").newInstance();

String sURL="jdbc:mysql://localhost:3306/DBName";
String sUserName="UserName";
String sPwd="Password";

conn = DriverManager.getConnection(sURL,sUserName,sPwd);

Statement stmt = conn.createStatement();


ResultSet rs = stmt.executeQuery("select * from tableName");
%>
<html>
<head>
<title>Simple JSP Java database connectivity</title>
</head>
<body>

</body>
</html> Subscribing to our newsletter
<%
if(conn!=null) Enter your email address
conn.close();
Subscribe
%>

Advance JSP connection by including connection file in connection required JSP Recent Posts
dbConn.jsp Java Access modifiers
Java Multiple Interface Inheritance
<% Java Interface Example with constant
Connection conn = null; Assignment error

Class.forName("com.mysql.jdbc.Driver").newInstance(); Learn Java Programming


JAVA Methods Example
String sURL="jdbc:mysql://localhost:3306/DBName";
Java – Types of EJB
String sUserName="UserName";
String sPwd="Password"; Java Comparable and Comparator Example
with Natural Sorting
conn = DriverManager.getConnection(sURL,sUserName,sPwd); Java Comparable Example
%> Java Class example
Java Interface Example
include this file in JSP w here connection is required Java Advance Inheritance Example
Java Multiple Inheritance Example
<%@ page language="java" import="java.sql.*"%>
<%@ include file="dbConn.jsp" %> Building a User Registration Application
<% Building a Login Application
Statement stmt = conn.createStatement();
Handling and stop Duplicate Form Submissions

converted by Web2PDFConvert.com
Handling and stop Duplicate Form Submissions
ResultSet rs = stmt.executeQuery("select * from tableName"); in Struts
%>
<html>
<head> Categories
<title>Simple JSP Advance Java database connectivity</title>
</head> HTML
<body> Java
JavaScript
</body>
</html> jQuery
<% JSP
if(conn!=null)
conn.close(); Misc
%> MySQL
Quiz
2. javaBean database connectivity
Struts
javaBean database connection is similar to JSP connection file. But all connection code is w ritten in
Tech News
a javaBean and this javaBean can be used in JSP file w ith JSP useBean tag to make connection
w ith database. Web Hosting

DBConnection.java XML & JAVA

package com.db; Polls


HTML and CSS are same?
import java.sql.Connection;
import java.sql.DriverManager; Yes, both are same
No, both are different
public class DBConnection {
Vote
public Connection getDBConnection() throws Exception{ View Results
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Most Popular Posts
String sURL="jdbc:mysql://localhost:3306/DBName"; Java - List Example
String sUserName="UserName";
String sPwd="Password"; Java - Map Example
Java - Vector Example
conn = DriverManager.getConnection(sURL,sUserName,sPwd);
return conn; Java - Queue Example
} Java - TreeSet Example
}
Java - How to convert String into Array
Java - Iterator Example
Use this javabean connection in JSP
Java - String contains() method example
<%@ page language="java" import="java.sql.*"%> Java - Set Example
<jsp:useBean id="dbConn" scope="request" class="com.db.DBConnection"/> JAVA - How to Add or Subtract Date
<%
Connection conn=dbConn.getDBConnection();
Statement stmt = conn.createStatement(); Featured Posts
ResultSet rs = stmt.executeQuery("select * from tableName");
%> Java - Choose best Database connectivity with
web application
<html>
<head> Java - Job Scheduling in web application with
<title>JavaBean java database connectivity</title> quartz API
</head> Struts2 Example, Struts2 Tutorials, Struts
<body> Program
User Login in JSP
</body>
</html> JSP Pagination
<% Top 10 jQuery Examples for Website
if(conn!=null)
conn.close();
%> Tutorials
JSP Tutorial
3. web.xml and servlet database connectivity
JDBC Tutorial
This is little good and advance technique of connectivity w ith database. We can define all HTML Tags
database variables in w eb.xml and on load of servlet w e can open connection in servlet’s init
method through javaBean. In this method, ServletConfig object can be used to get variable
parameter field name and value. This method is flexible and can change database name, server Tag Cloud
name, user and passw ord in w eb.xml file w ithout changing in the source code.
web.xml arraylist Calendar Collections
Database Data types EJB HTML Java java.io
<servlet>
<servlet-name>DBInit</servlet-name> Java Statements jQuery JSP Math Programs
<servlet-class>com.db.DBInit</servlet-class>
<init-param>
runtime Select sorting SQL String
<param-name>DriverName</param-name> StringBuffer StringBuilder Struts struts2
<param-value>com.mysql.jdbc.Driver</param-value> struts examples Tomcat typecast Web application
</init-param>
<init-param>
Link us
<param-name>ServerName</param-name>
<param-value>localhost</param-value>
</init-param> Link to Us

converted by Web2PDFConvert.com
<init-param>
<param-name>Port</param-name>
<param-value>3306</param-value>
Write for Easywayserver
</init-param>
<init-param>
<param-name>DatabaseName</param-name> EasyWayServer is most popular w ebsite in w eb
professionals. Our reach to view er is more than half
<param-value>dbName</param-value> million each month. Get recognized in the w eb
</init-param> community by w riting for us.
<init-param> Send your articles at submit@easywayserver.com
<param-name>UserName</param-name>
<param-value>userName</param-value>
</init-param> Thank you
<init-param>
<param-name>Password</param-name> I am not begging for donations, if you like this w ebsite
<param-value>yourPassword</param-value> please help me to improve, link this w ebsite and share
</init-param> w ith friends.
<load-on-startup>1</load-on-startup> Thank you very much
</servlet>

Servlet to initialize the values


DBInit.java

package com.db;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import com.db.DBConnection;

public class DBInit extends HttpServlet {

public void init(ServletConfig config) throws ServletException {

String jdbcDriverName=config.getInitParameter("DriverName");
String jdbcServerName=config.getInitParameter("ServerName");
String jdbcPort=config.getInitParameter("Port");
String jdbcDatabaseName=config.getInitParameter("DatabaseName");
String jdbcUserName=config.getInitParameter("UserName");
String jdbcPassword=config.getInitParameter("Password");

ServletContext sc = config.getServletContext();
// set in application scope of web application to access in future

DBConnection dbConn=null;

try{
dbConn=new DBConnection();

dbConn.setSDriverName(jdbcDriverName);
dbConn.setSServerName(jdbcServerName);
dbConn.setSPort(jdbcPort);
dbConn.setSDatabaseName(jdbcDatabaseName);
dbConn.setSUserName(jdbcUserName);
dbConn.setSPassword(jdbcPassword);

sc.setAttribute("dbConn", dbConn);

}
catch(Exception e)
{
e.printStackTrace();
}

DBConnection.java

package com.db;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {

public String sDriverName=null;


public String sServerName=null;
public String sPort=null;
public String sDatabaseName=null;
public String sUserName=null;
public String sPassword=null;

public String getSDriverName() {


return sDriverName;

converted by Web2PDFConvert.com
return sDriverName
}

public void setSDriverName(String driverName) {


sDriverName = driverName;
}

public String getSServerName() {


return sServerName;
}

public void setSServerName(String serverName) {


sServerName = serverName;
}

public String getSPort() {


return sPort;
}

public void setSPort(String port) {


sPort = port;
}

public String getSDatabaseName() {


return sDatabaseName;
}

public void setSDatabaseName(String databaseName) {


sDatabaseName = databaseName;
}

public String getSUserName() {


return sUserName;
}

public void setSUserName(String userName) {


sUserName = userName;
}

public String getSPassword() {


return sPassword;
}

public void setSPassword(String password) {


sPassword = password;
}

public Connection getDBConnection() throws Exception{


Connection conn = null;
Class.forName(sDriverName).newInstance();

String sURL ="jdbc:mysql://"+sServerName+":"+sPort+"/"+sDatabaseName;

conn = DriverManager.getConnection(sURL,sUserName, sPassword);


return conn;
}
}

Connection can be used in JSP as show n in this JSP file

<%@ page language="java" import="java.sql.*"%>


<jsp:useBean id="dbConn" scope="application" class="com.db.DBConnection"/>
<%
Connection conn=dbConn.getDBConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from tableName");
%>
<html>
<head>
<title>web.xml and Servlet database connectivity</title>
</head>
<body>
<%
while(rs.next())
{
rs.getString("id");
}
%>
</body>
</html>
<%
if(conn!=null)
conn.close();
%>

4. properties file database connectivity

W hen you need more flexible environment of w eb application and database connectivity,

converted by Web2PDFConvert.com
properties file is another good option for database connectivity. You can change database
variable name w ithout changing restarting w eb server and w ithout changing in java source code.
In this technique w e have to use properties file and define all database variables values in this
file. This properties value can be accessed through ResourceBundle of java. Connection code can
be w ritten in javaBean or in JSP file to make connection.
This properties file should be copied in W EB-INF/classes folder

connection_config.properties

# Usually com.mysql.jdbc.Driver
driver.name=com.mysql.jdbc.Driver

# Usually localhost
server.name=localhost

# Usually 3306
port.no=3306

# Usually project
database.name=dbName

# Usually you define


user.name=UserName

# Usually you define


user.password=Password

javaBean is used to make connection


DBConnection.java

package com.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ResourceBundle;

public class DBConnection {

public String sDriverName=null;


public String sServerName=null;
public String sPort=null;
public String sDatabaseName=null;
public String sUserName=null;
public String sPassword=null;

public Connection getDBConnection() throws Exception{


Connection conn = null;

ResourceBundle rb=ResourceBundle.getBundle("connection_config");

sDriverName=rb.getString("driver.name");
sServerName=rb.getString("server.name");
sPort=rb.getString("port.no");
sDatabaseName=rb.getString("database.name");
sUserName=rb.getString("user.name");
sPassword=rb.getString("user.password");

Class.forName(sDriverName).newInstance();

String sURL ="jdbc:mysql://"+sServerName+":"+sPort+"/"+sDatabaseName;

conn = DriverManager.getConnection(sURL,sUserName, sPassword);


return conn;
}
}

connection can be used in JSP file

<%@ page language="java" import="java.sql.*"%>


<jsp:useBean id="dbConn" scope="request" class="com.db.DBConnection"/>
<%
Connection conn=dbConn.getDBConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from tableName");
%>
<html>
<head>
<title>properties file database connectivity</title>
</head>
<body>
<%
while(rs.next())
{
rs.getString("id");
}

converted by Web2PDFConvert.com
%>
</body>
</html>
<%
if(conn!=null)
conn.close();
%>

5. XML file database connectivity

W hen your application is more focused on XML based pattern. You can use XML file to make
database connection in java. XML is getting more popularity and easy to handle use and
implement in w eb application. These results, w e can define all database properties in XML node
tree. These values can be getting from any XML parser. Connection code can be defined in
javaBean and in JSP file. This is more flexible method. We do not have to restart w eb server w hen
w e do change in XML file and no change w ill be required to do in source code.
dbConnection.xml

<?xml version="1.0" encoding="iso-8859-1"?>


<connection-config>
<driverName>com.mysql.jdbc.Driver</driverName>
<serverName>localhost</serverName>
<port>3306</port>
<databaseName>dbName</databaseName>
<userName>root</userName>
<pwd></pwd>
</connection-config>

DBConnection.java

package com.db;

import java.sql.Connection;
import java.sql.DriverManager;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class DBConnection {

public String sDriverName=null;


public String sServerName=null;
public String sPort=null;
public String sDatabaseName=null;
public String sUserName=null;
public String sPassword=null;

public Connection getDBConnection() throws Exception{


Connection conn = null;

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db =dbf.newDocumentBuilder();
Document doc=db.parse("c:\\tomcat\\webapps\\myApp\\dbConnection.xml");

NodeList driverName = doc.getElementsByTagName("driverName");


NodeList serverName = doc.getElementsByTagName("serverName");
NodeList port = doc.getElementsByTagName("port");
NodeList databaseName = doc.getElementsByTagName("databaseName");
NodeList userName = doc.getElementsByTagName("userName");
NodeList pwd = doc.getElementsByTagName("pwd");

Node nDriverName = driverName.item(0);


sDriverName=nDriverName.getFirstChild().getNodeValue().trim();

Node nServerName = serverName.item(0);


sServerName=nServerName.getFirstChild().getNodeValue().trim();

Node nPort = port.item(0);


sPort=nPort.getFirstChild().getNodeValue().trim();

Node nDatabaseName = databaseName.item(0);


sDatabaseName=nDatabaseName.getFirstChild().getNodeValue().trim();

Node nUserName = userName.item(0);


sUserName=nUserName.getFirstChild().getNodeValue().trim();

Node nPwd = pwd.item(0);


sPassword=nPwd.getFirstChild().getNodeValue().trim();

Class.forName(sDriverName).newInstance();

String sURL ="jdbc:mysql://"+sServerName+":"+sPort+"/"+sDatabaseName;

conn = DriverManager.getConnection(sURL,sUserName, sPassword);


return conn;
}

converted by Web2PDFConvert.com
}

Use in JSP

<%@ page language="java" import="java.sql.*"%>


<jsp:useBean id="dbConn" scope="request" class="com.db.DBConnection"/>
<%
Connection conn=dbConn.getDBConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from tableName");
%>
<%
if(conn!=null)
conn.close();
%>

6. Connection pooling in java database connectivity

Connection pooling gives good performance on database connectivity over all previous database
connection. How it increase performance and efficiency of the database connectivity. W hen w e
open new connection in database and after using that connection w e closed that connection and
it returns again to the connection pool for next w aiting. The next time w hen you need a
connection w ith database, it takes connection from connection pool and reuses the previous
connection.

This is database Connection Pooling with Tomcat


tomcat/config/context.xml

<?xml version='1.0' encoding='utf-8'?>

<Context>

<WatchedResource>WEB-INF/web.xml</WatchedResource>

<Resource name="jdbc/PooledDB"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
username="DBUserName"
password="DBPassword"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dbName?autoReconnect=true"
maxWait="1000"
removeAbandoned="true"
maxActive="30"
maxIdle="10"
removeAbandonedTimeout="60"
logAbandoned="true"/>

</Context>

Copy mysql-connector-java.jar MySQL jdbc driver in tomcat/lib folder


DBConnection.java

package com.db;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBConnection {

public static Connection getConnection() throws Exception


{
return getPooledConnection();
}

public static Connection getPooledConnection() throws Exception{


Connection conn = null;

try{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("No Context");

DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/PooledDB");

if (ds != null) {
conn = ds.getConnection();
return conn;
}else{
return null;
}

converted by Web2PDFConvert.com
}catch(Exception e) {
e.printStackTrace();
throw e;
}
}
}

connection can be used in JSP file

<%@ page language="java" import="java.sql.*"%>


<jsp:useBean id="dbConn" scope="request" class="com.db.DBConnection"/>
<%
Connection conn=dbConn.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from tableName");
%>
<%
if(conn!=null)
conn.close();
%>

On the basis of all connection method, you can use best suitable method in your application to
make database connection.

Related Posts:
Java database connectivity w ith mysql
JAVA – How to read XML file
Java – Insert Image in Database
JSP Pagination
User Login in JSP
JAVA – Read XML Taglib and JSTL in JSP

Bookmark

DataDirect ODBC
Connect SQ L, Sybase, DB2 & More. Easy
Install & Adm in. Download Now!
www.datadirect.com /O DBC

11 Responses to “Java – Choose best Database connectivity with web application


alex says:
July 28, 2009 at 12:21 am
after point 3 data is missing. kindly rectify the error. this document is very useful i feel…

alex says:
July 28, 2009 at 12:22 am
kindly add the rest of the data after point 3

Object says:
August 11, 2009 at 4:05 am
This is very good to have all connection mechanisms at one place. Thank you and I appreciate your effort. Keep
posting useful stuff like this.

converted by Web2PDFConvert.com
harpreet says:
September 26, 2009 at 7:24 pm
This is the best article for the newbees i know how hard to get these things for the first time,
THANK YOU SO MUCH FOR THE EFFORT and keep up the good work ,
thank you

Zaprogrammer says:
November 21, 2009 at 3:39 pm
Thnx alot for this gr8 effort !! Really v. useful the helpful

Many thnx

balu says:
January 8, 2010 at 12:08 pm
nice article

thank you.

cdreader says:
March 11, 2010 at 1:42 pm
nice artical

krish says:
April 2, 2010 at 11:59 pm
Hi,
Thanks for this informative article.
Helps newbies like me get more ideas.

You have given the sample code, however can you pls tell me what needs to be done if the database is stored in a different
directory.
Is there a specific directory where we need to store the database?

I am trying to use Derby Java DB with Tomcat for a small experiment for learning, but am stuck.
Thanks.

Gelani says:
May 9, 2010 at 6:37 am
HI,

All examples are very good.


I appreciate your help.keep up the good work.
Thanks

Jean says:
August 12, 2010 at 10:48 pm
One thing missing from your connection pooling example is the release of objects and being prepared for exceptions.
Might consider adding both how to effectively release an object back to the pool and using try/catch/finally to ensure
nothing is ever broken and left to become a nice old memory leak…

Azhar says:
December 9, 2010 at 11:32 am
Great Article….explained really well….No Doubts at all….keep it up Thanks

Leave a Reply
Name (required)

Mail (will not be published) (required)

Website
Security Code:

converted by Web2PDFConvert.com
Submit Comment

Random Post
Java Calendar - How to get Month Name
Properties in JAVA
Confirm Javascript
Struts2 - File tag example
JSP - How to get IP address of client machine
How to delete file in JAVA
Java - How to get size of Map
JavaScript - Select all checkboxes
Java - How to get size of Queue
Free Real Estate Source Code
Struts2 - Input text tag example
Java - How to get size of Hashtable
HTML - <a> Anchor Tag
Java - How to clear list
Java - StringBuffer length() Example, StringBuffer length() program, Calculate Length

Privacy Policy

converted by Web2PDFConvert.com

You might also like