Web >> Development >> Java Servlet >> Examples >> 

Assumptions 1. the server has MySQL installed location with database named "DBName" and username "mysqluser" and password "mysqlpassword" 2. there is a table named "kb" Servlet ======= import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class ReadKB extends HttpServlet { private Connection conn; public void init() { String driver = "com.mysql.jdbc.Driver"; try { // Load database driver Class.forName(driver); // Establish connection to database conn = DriverManager.getConnection("jdbc:mysql://localhost/DbName","mysqluser", "mysqlpassword"); } catch(ClassNotFoundException cnfe) { } catch(SQLException sqle) { } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // If no connection, then display server error page if(conn == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database connection could not be established"); return; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { Statement statement = conn.createStatement(); String query = "SELECT * from kb"; // Send query to database obtain resultset ResultSet rs = statement.executeQuery(query); out.println("<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><body><br><table border='1'>"); int columns = rs.getMetaData().getColumnCount(); // display columns as table headers out.println("<tr>\n"); for (int i=1; i<= columns; i ) { String columnName = rs.getMetaData().getColumnName(i); out.println("<td>" columnName "</td>"); } out.println("</tr>\n"); // display row data as table rows while(rs.next()) { // display resultset rows as table rows out.println("<tr>\n"); for (int i=1; i<= columns; i ) { String columnName = rs.getMetaData().getColumnName(i); String columnValue = rs.getString(i); out.println("<td>" columnValue "</td>"); } out.println("</tr>\n"); } out.println("</table></body></html>"); rs.close(); statement.close(); } catch(SQLException sqle) { out.println("Database error: " sqle "<p>"); } } public void destroy() { // close connection try { conn.close(); } catch(SQLException sqle) { } } }

Deals @yubeshop.com