Saturday 5 April 2014

Using JDBC thin client to connect to Oracle - A sample JSP.

<!--This is a program written in HTML JSP embedded. This program use JDBC thin client to connect to Oracle 11g. Page gives user to select from 2 checkbox options and uses post method  two create criteria for SQL query. A single file is used for both post and get method, two separate form is used for post and get method.-->

<html>
<head>
  <title>Employee</title>
</head>
<body>
  <h1>Employee Details</h1>
  <h3>Choose Grade(s):</h3>
  <form method="get">
    <input type="checkbox" name="grade" value="Worker">Worker
    <input type="checkbox" name="grade" value="Staff">Staff
    <input type="submit" value="Query">
  </form>

  <%@ page import = "java.sql.*" %>
  <%
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@[ipaddress or hostname]:portnumber:sid","username","password";
    Statement stmt = conn.createStatement();
    String sql="select emp_code,emp_name,date_of_birth,emp_sex from employee_master";
    String[] grade = request.getParameterValues("grade");
if (grade != null)
    {
    if(grade.length>0)
        {
        sql+=" where emp_grade in (";
        int i;
        for (i = 0; i < grade.length; ++i)
        {
        sql+="'" + grade[i].charAt(0) + "'";
        if(i<grade.length-1)
        sql+=",";
        }
        sql+=")";
        sql+=" and status='A' order by emp_name";
        %>
        <hr>
        <form method="get" action="dbconn.jsp">
        <tr> <%
            try
            { %>
              <table border=1 cellpadding=5><tr><td> Emp Code</td><td>Emp Name</td><td>DOB</td><td>Sex</td><td><%=sql%></td></tr>
            <%  ResultSet rs = stmt.executeQuery(sql);
              while (rs.next()) {
          %>
                  <tr>
                    <td><%= rs.getString("emp_code") %></td>
                    <td><%= rs.getString("emp_name") %></td>
                    <td>$<%= rs.getString("date_of_birth") %></td>
                    <td><%= rs.getString("emp_sex") %></td>
                  </tr>
          <%
              }
          %>
                </table></form>
              <a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>
          <%
              rs.close();
            }
            catch(SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
      stmt.close();
      conn.close();
  %>
</body>
</html>

No comments: