PDA

View Full Version : connecting databse through servlet


tanvirtonu
06-05-2009, 12:17 PM
I came to know that it is better connect to database from a servlet than a jsp.
Now.I have a jsp file which I like to use to connect to my database.Now how can I add/call a servlet from my jsp file and after adding how to get the properties/methods of my servlet which connects the database.Could anybody help me?
Can I use a java bean to connect to database.I know using bean with jsp.But is it the proper way?

leneena
06-05-2009, 11:59 PM
Hi,
I guess i can help u with this.
You u need a servlet DAO class in which u need to create a connection and the code looks like this...

Connection con = null;
Statement st = null;
ResultSet rs = null;
LinkedHashSet emp_set = null;
Employee emp = null;
try
{
/* Establishing the connections */
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521 :ORCL","scott","tiger");
st = con.createStatement();
rs = st.executeQuery(qry);
System.out.println("connection established");
emp_set=new LinkedHashSet();
while(rs.next())
{
/* For a single record in the emp table */
emp = new Employee();
emp.empid = rs.getInt("EMPNO");
emp.empname = rs.getString("ENAME");
emp.empsal = rs.getFloat("SAL");
emp.empjob = rs.getString("JOB");
emp_set.add(emp);
}//try
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
rs.close();
st.close();
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}//finally

This is a DAO class and we need to write a session in a JSP page

HttpSession empsession = request.getSession(true);
empset = (LinkedHashSet)empsession.getAttribute("emp_set");
if(empset == null)
{
empset = emp.getEmployee("");
empsession.setAttribute("emp_set", empset);
}
//put all the logic in a session
String emp_sort = "empid";
String emp_sort_value = null;
if((empsession.getAttribute("emp_sort_type")) == null)
{
empsession.setAttribute("emp_sort_type","empid");
}

Regards,
Leneena