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.
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:
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) {
System.out.println("sorry********************"+e);
e.printStackTrace();
}
}
The servlet class:
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) {
System.out.println("sorry**************************");
e.printStackTrace();
}