Introduction
Please refer to my first part Storing compilation and deployment of Servlet
First, create an employee table in Oracle and insert some data as below.
- 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)
Creation of dsn(database source name)
Start-Control Panel- Administrative Tools- Data Sources (ODBC)-go to system DSN tab-click add button-select a driver for which you want to set up a data source (for Oracle- Oracle in XE)-select it and click finish-give any name in data source name textbox-then click ok button.
Program to display data from database through servlet and JDBC
- 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");
- }
- }
- }


Sandeep SharmaPosted Jun 27, 2013, 7:14 AM
Sir, how to establish java connection with sql server2012?
Sandeep SharmaPosted May 9, 2013, 12:53 AM
good one.....
Rohatash KumareditedPosted Jul 28, 2011, 4:27 AMEdited Jul 28, 2011, 4:27 AM
Good article for beginners. Keep it up....
Angelina ErinPosted Jul 28, 2011, 4:09 AM
Helpful Article