import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InsertServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("");
out.print(" out.print( req.getRequestURI() );
out.print("\" method=\"post\">");
out.print("First Name :
");
out.print("
");
out.print("Last Name :
");
out.print("");
out.print("
");
out.print(" Insert Record");
out.print(" ");
out.print(" Display Records");
out.print("");
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("");
out.print("
");
out.println("ID\tFirst Name\tLast Name\n");
// receiving parameters
String first = req.getParameter("first").trim();
String last = req.getParameter("last").trim();
boolean proceed = false;
if(first != null && last != null)
if(first.length() > 0 && last.length() > 0)
proceed = true;
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:odbc_exmp");
String sql;
sql = "INSERT INTO Names(first_name, last_name) VALUES (?,?)";
ps = con.prepareStatement(sql);
stmt = con.createStatement();
// inserting records
if(proceed) {
ps.setString(1, first);
ps.setString(2, last);
ps.executeUpdate();
}
// displaying records
rs = stmt.executeQuery("SELECT * FROM Names");
while(rs.next()) {
out.print(rs.getObject(1).toString());
out.print("\t");
out.print(rs.getObject(2).toString());
out.print("\t\t");
out.print(rs.getObject(3).toString());
out.print("\n");
}
} catch (SQLException e) {
throw new ServletException(e);
} catch (ClassNotFoundException e) {
throw new ServletException(e);
} finally {
try {
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
if(ps != null)
ps.close();
if(con != null)
con.close();
} catch (SQLException e) {}
}
out.print("");
out.close();
}
}
No comments:
Post a Comment