In order to connect to database you need to add mysql-connector-java-5.1.22.jar file in your eclipse project as a external jar file....
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public
class HelloServlet extends HttpServlet {
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head><title>Students List</title></head>");
out.println("<body>");
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception E) {
out.println("Unable to load driver.");
E.printStackTrace();
}
out.println("<br><center><p style=color:purple;font-size:30px;>STUDENTS DATABASE</p></center><hr>");
try {
Connection Conn =
DriverManager.getConnection("jdbc:mysql://localhost/saran","root","root");
// Do something with the Connection
Statement Stmt = Conn.createStatement();
ResultSet RS = Stmt.executeQuery("SELECT * from student");
out.println("<center><table border='1' style=color:purple;font-size:20px;><th>Name</th><th>Area</th><th>Course</th>");
while (RS.next()) {
out.println("<tr><td>"+RS.getString("name")+"<td>"+RS.getString("area")+"<td>"+RS.getString("course")+"</td></tr>");
}
out.println("</table></center>");
out.println("<center><form action='index.htm'><input type='submit' value='Home'></form></center>");
// Clean up after ourselves
RS.close();
Stmt.close();
Conn.close();
}
catch (SQLException E) {
}
out.println("</body></html>");
}
}
Java programs for beginners, list of programs in java on various topics, interesting programs in java. Java programs on various topics
Saturday, February 23, 2013
Servlet Program for Retrieving data from Table
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Please post your comments. Your comments make us to write more programs for you.