Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I have created a database connection using servletcontext. In this code when I login for the first time, it will exceute sucessfully but when I use it again, it will throw a sql exception. I don't understand what the problem is

The code is as follows.
The servlet context classss.

Java
public void contextInitialized(ServletContextEvent arg0) {
ServletContext sc = arg0.getServletContext();
String url=sc.getInitParameter("url");
String user=sc.getInitParameter("username");
String pass= sc.getInitParameter("password");
database db = new database(url, user, pass);
System.out.println("hello*******************************************************************************");
sc.setAttribute("db", db);
}


Database connection class:
Java
Connection con = null;
public database(String url,String user, String pass) {
       try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                this.con = DriverManager.getConnection(url,user,pass);
           } catch (Exception e) {
             // TODO Auto-generated catch block
             System.out.println("sorry********************"+e);
             e.printStackTrace();
           }
}


The servlet class:
Java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String user= request.getParameter("username");
		String password= request.getParameter("password");
		
	database db = (database)getServletContext().getAttribute("db");
	try {
		PreparedStatement ps = db.con.prepareStatement("select * from admintable where vusername=? and vpassword=?");
		ps.setString(1,user);
		ps.setString(2, password);
		ResultSet rs= ps.executeQuery();
		if(rs.next())
		{
			System.out.println("************login sucessfully*******************");
			PrintWriter out=response.getWriter();
			out.println("hello arunnarwal");
			db.con.close();
			
			
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		System.out.println("sorry**************************");
		e.printStackTrace();
}
Posted
Updated 23-Jan-12 8:40am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900