Java Project JSP JDBC Java Program Core Java Demo MORE

Retrieve data from MySQL using Servlet and JDBC


create table employee(empid varchar(10),empname varchar(10),sal int)    
      
insert into employee values('e001','raj',10000)    
insert into employee values('e002','harry',20000)    
insert into employee values('e003','sunil',30000)    
insert into employee values('e004','pollock',40000)    
insert into employee values('e005','jonty',50000)    
insert into employee values('e006','kallis',60000)    
insert into employee values('e007','richard',70000)   
	

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
import java.sql.*;  
    
public class display extends HttpServlet  
{    
     public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException 
      {  
         PrintWriter out = res.getWriter();  
         res.setContentType("text/html");  
         out.println("<html><body>");  
         try 
         {  
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
             Connection con = DriverManager.getConnection("jdbc:odbc:mydsn", "system", "pintu");  
             // Here dsnname- mydsn,user id- system(for oracle 10g),password is pintu.  
             Statement stmt = con.createStatement();  
             ResultSet rs = stmt.executeQuery("select * from employee");  
             out.println("<table border=1 width=50% height=50%>");  
             out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");  
             while (rs.next()) 
             {  
                 String n = rs.getString("empid");  
                 String nm = rs.getString("empname");  
                 int s = rs.getInt("sal");   
                 out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");   
             }  
             out.println("</table>");  
             out.println("</html></body>");  
             con.close();  
            }  
             catch (Exception e) 
            {  
             out.println("error");  
         }  
     }  
 }  

web.xml setting

<?xml version="1.0" encoding="ISO-8859-1"?>  
<!--  
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  
  
http://www.apache.org/licenses/LICENSE-2.0  
  
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.  
-->  
  
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">  
  
    <servlet>  
        <servlet-name>display</servlet-name>  
        <servlet-class>display</servlet-class>  
    </servlet>  
  
    <servlet-mapping>  
        <servlet-name>display</servlet-name>  
        <url-pattern>/display</url-pattern>  
    </servlet-mapping>  
</web-app>  
	

Step 4 : To use this class method, create an object in Java Servlet program

Below program shows Servlet Class which create a connection and insert the data in the demo table,

import java.io.IOException; 
import java.io.PrintWriter; 
import java.sql.Connection; 
import java.sql.PreparedStatement; 

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

/* Import Database Connection Class file */
import code.DatabaseConnection; 

/* Servlet Name */
@WebServlet("/InsertData") 
public class InsertData extends HttpServlet { 
	private static final long serialVersionUID = 1L; 

	protected void doPost(HttpServletRequest request, 
HttpServletResponse response) 
		throws ServletException, IOException 
	{ 
		try { 

			/* Initialize the database */
			Connection con = DatabaseConnection.initializeDatabase(); 

			/* Create a SQL query to insert data into demo table */
			/* demo table consists of two columns, so two '?' is used */
			PreparedStatement st = con 
				.prepareStatement("insert into demo values(?, ?)"); 

			/* For the first parameter, */
			/* get the data using request object */
			/* sets the data to st pointer */
			st.setInt(1, Integer.valueOf(request.getParameter("id"))); 

			/* Same for second parameter */
			st.setString(2, request.getParameter("string")); 

			/* Execute the insert command using executeUpdate() */
			/* to make changes in database */
			st.executeUpdate(); 

			/* Close all the connections */
			st.close(); 
			con.close(); 

			/* Get a writer pointer */
			/* to display the successful result */
			PrintWriter out = response.getWriter(); 
			out.println("<html><body><b>Successfully Inserted"
						+ "</b></body></html>"); 
		} 
		catch (Exception e) { 
			e.printStackTrace(); 
		} 
	} 
}