Creating Database Connection in Context.xml

<Context>
  <Resource name="jdbc/[YourDatabaseName]"  auth="Container" type="javax.sql.DataSource"
   username="[DatabaseUsername]" password="[DatabasePassword]" driverClassName="com.mysql.jdbc.Driver"
   url="jdbc:mysql:/[yourserver]:3306/[yourapplication]" maxActive="15" maxIdle="3"/>
</Context>

context.xml

<Context>
  <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000" username="root" password="" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/test"/>
  <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Test.java

 PrintWriter out = response.getWriter();
 String Sno = request.getParameter("t1");
 String Name = request.getParameter("t2");
		
 try{
   InitialContext context = new InitialContext();
   DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/test");
   Connection conn  = ds.getConnection();
   PreparedStatement statement = conn.prepareStatement("insert into Details values(?,?)");
   statement.setString(1, Sno);
   statement.setString(2, Name);
   statement.execute();
   conn.close();
   statement.close();
   out.println("Done");
  }catch (Exception e) {
   e.printStackTrace();
  }

Comments are closed.