Created
December 2, 2012 15:21
-
-
Save PrabhjotSingh/4189304 to your computer and use it in GitHub Desktop.
How to connect your Servlet with Database in Eclipse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> | |
| <html> | |
| <head> | |
| <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> | |
| <title>Insert title here</title> | |
| </head> | |
| <body> | |
| <form action="MyServlet" method="get"> | |
| Enter the ID of Student | |
| <input type="text" name="num"><br> | |
| <input type="Submit" value="Submit"> | |
| </form> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * View full program at http://java.directref.com/?p=368 | |
| */ | |
| import java.io.*; | |
| import javax.servlet.*; | |
| import javax.servlet.http.*; | |
| import java.sql.*; // for database purpose | |
| public class MyServlet extends HttpServlet | |
| { | |
| Connection con; | |
| Statement stmt; | |
| ResultSet rs; | |
| public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException | |
| { | |
| response.setContentType("text/html"); // informing the client that which format of data/response will be send | |
| PrintWriter out= response.getWriter(); | |
| String name= request.getParameter("num"); | |
| // will retrieve "NUM" field value entered by user using "getParameter()" | |
| // and store in STRING "name" | |
| try | |
| { | |
| Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); | |
| con= DriverManager.getConnection("Jdbc:Odbc:dbs123"); | |
| stmt= con.createStatement(); | |
| rs=stmt.executeQuery("Select * from Student where s_name= '"+name+"' "); | |
| // Retrieving all columns from Database where "name" matches | |
| // Name of table is "Student" | |
| if(rs.next()) | |
| { | |
| out.println("<h3> Name=</h3>" +rs.getString("s_name")); // Printing Name from Database | |
| out.println("<br> Address=" +rs.getString("address")); // Printing Address from Database | |
| } | |
| else | |
| { | |
| out.println("<h3> ID is not exists</h3>"); // If no such ID found in Database | |
| } | |
| } | |
| catch(Exception e) | |
| { | |
| out.println(e); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment