Newsletter

How to Connect Servlet to the Database with Example

Servlets » on Feb 7, 2013 { 18 Comments } By Sivateja

Let us see how to connect servelet application with (Oracle) database, for time being i am considering Oracle XE.  In our application i am going to display all the records from the table ‘Java4s‘.

  • Make sure you have java4s table in the database with some data in it
  • Make sure you have ojdbc14.jar file in your classpath and lib folder as well as [ why in two places ? 🙂 servlet will use ojdbc14.jar file which is in the classpath, for compiling the application, and ojdbc14.jar file in lib folder will be used at the time of running the servlet application], you can check the same in this figure…

Directory Structure

Files Required

  • index.html
  • ServletDatabaseConnect.java
  • web.xml
  • ojdbc14.jar

index.html

<form action="show" method="post">
  <font face="verdana" size="2">
     Enter Table Name :<input type="text" name="table"> 
                       <input type="submit" value="Display">
  </font>
</form>

ServletDatabaseConnect.java

package java4s;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDatabaseConnect extends HttpServlet  
{
    protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
    {
        PrintWriter pw=res.getWriter();
        res.setContentType("text/html");        
        String tb=req.getParameter("table");    

        try
        {
             Class.forName("oracle.jdbc.driver.OracleDriver");
             Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
             Statement st=con.createStatement();
             System.out.println("connection established successfully...!!");     

             ResultSet rs=st.executeQuery("Select * from "+tb);

             pw.println("<table border=1>");
                 while(rs.next())
                 {
                     pw.println("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td>"+
                                      "<td>"+rs.getString(3)+"</td></tr>");
                 }
             pw.println("</table>");
             pw.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
}

web.xml

<web-app>

    <servlet>
        <servlet-name>ServletDBConnect</servlet-name>
        <servlet-class>java4s.ServletDatabaseConnect</servlet-class>    

    </servlet>

    <servlet-mapping>
            <servlet-name>ServletDBConnect</servlet-name>
            <url-pattern>/show</url-pattern>
    </servlet-mapping>

</web-app>

Output

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

18 Responses to “How to Connect Servlet to the Database with Example”
  1. what is the difference between flush and commit?

  2. Akhilesh says:

    Hello sir ! i love ur tutorial..u r doing great work…plz post also jdbc ,jsp and sir in servlet u dont cover all topic..plz also post session ,filter etc..thankx in advance

  3. sidhu says:

    what the means of sqlexception?
    and which situation it will come
    plzz explain

  4. ASRAAR says:

    Hi !!!!!
    Can anyone explain filters in detail with code segments? like we have authentication filter , logging, data compression etc.

  5. Kannan K says:

    Sir ur tutorial is realy useful and could u pls add Servlet Chaining & session tracking in servlet

  6. Raju says:

    hi sir,
    We are eagerly wait for web servies, please provide the implementation of web services ASAP. Thankx a lot.

  7. srikanth says:

    hello sir,
    i want webservice tutorials please provide webservices ASAP,we have so many websites but not equal to your explanation,your explanation is very neat and clearly please provide webservices

    thank youuuuuuuu

  8. MSREDDY says:

    First for providing all topics in software but i need jsp tutorials

  9. RaviReddy says:

    jdbc ok
    can u tell how to connect servlet and hibernate
    login and registration form

  10. nagesh says:

    Very helpful tutorial.Thank you

  11. Sanjeet Kumar says:

    Making connection SQL server Database

    Using the sqljdbc.jar class library, applications must first register the driver as follows:

    Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);

    When the driver is loaded, you can establish a connection by using a connection URL and the getConnection method of the DriverManager class:

    String connectionUrl = “jdbc:sqlserver://localhost:1433;” +
    “databaseName=AdventureWorks;user=MyUserName;password=*****;”;
    Connection con = DriverManager.getConnection(connectionUrl);

  12. Alexander says:

    Many thanks.

  13. Gayatri says:

    Thank you for good explaination.

  14. Manoj Soni says:

    Very help full tutorial but plz update complete topic and plz update jsp tutorial..

  15. Vivek Dubey says:

    thanks sir for good explanation.

  16. Nagababu says:

    Thanks sir, I am expecting JSP tutorial Please….

  17. sudha says:

    Hello sir, I am getting the "connection established successfully…!!" message but, am not retrieve my table in the final output. so, please give me the advice. thank you

  18. Soumya says:

    Please explain servlet filters and file uploading

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.