A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Fetching data (int & String types) from database mysql in Servlet

Create a database as below:




Now insert values in the tables as below:




Now create a servlet DatabaseAccess.java which is as follow:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class DatabaseAccess extends HttpServlet{
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      //define response content type
      response.setContentType("text/html");
     
      //use getWriter method on PrintWriter out object
      PrintWriter out = response.getWriter();
          
      try{

         // load driver
         Class.forName("com.mysql.jdbc.Driver");

         //manager connection and check driver
         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login_test", "root", "pass");

         // Execute SQL query
         Statement stmt = conn.createStatement();
         String sql;
         sql = "SELECT id, first, last, age FROM Employees";
         ResultSet rs = stmt.executeQuery(sql);

         // Extract data from result set
         while(rs.next()){
            //Retrieve by column name
            int id  = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            //Display values
            out.println("ID: " + id + "<br>");
            out.print(", Age: " + age + "<br>");
            out.print(", First: " + first + "<br>");
            out.print(", Last: " + last + "<br>");
         }
         out.println("</body></html>");

         rs.close();
         stmt.close();
         conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }catch(Exception e){
         e.printStackTrace();
      }
      }
   }


Now, run this project, we will get output as below:


LEARN TUTORIALS

.

.