Professional Documents
Culture Documents
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
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.
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);
</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
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
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>
package com.db;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import com.db.DBConnection;
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;
converted by Web2PDFConvert.com
return sDriverName
}
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
package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ResourceBundle;
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();
converted by Web2PDFConvert.com
%>
</body>
</html>
<%
if(conn!=null)
conn.close();
%>
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
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;
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db =dbf.newDocumentBuilder();
Document doc=db.parse("c:\\tomcat\\webapps\\myApp\\dbConnection.xml");
Class.forName(sDriverName).newInstance();
converted by Web2PDFConvert.com
}
Use in JSP
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.
<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>
package com.db;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
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;
}
}
}
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
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,
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)
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