package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; /** Test servlet for JDBC: Display the books table as an HTML table. This servlet assumes that this table exists with the following structure
CREATE TABLE books ( isbn CHAR(15) PRIMARY KEY NOT NULL, title VARCHAR(100) NOT NULL, author VARCHAR(100) NOT NULL, pub VARCHAR(20) NOT NULL, year year NOT NULL, price DECIMAL(9,2) DEFAULT NULL };*/ public class BookDisplayServlet0 extends HttpServlet { private Connection connection; private PreparedStatement getBooks; /** Initialize the servlet by connecting to the database and preparing a select query for the books in the books table. */ public void init() throws ServletException { try { // Load the driver: tomcat will use the classpath // webapps\test\WEB-INF\lib to find the jar file containing // the classes. Note that the java compiler does not need // to know the whereabouts of the driver since the driver // is loaded dynamically at run time. Class.forName("com.mysql.jdbc.Driver"); // Make a database connection to the bookstore database connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/web_db", "c2206", "c2206"); // Prepare a statement that can be used to send the query getBooks = connection.prepareStatement("SELECT * FROM books"); } catch (Exception e) { e.printStackTrace(); throw new UnavailableException(e.getMessage()); } } /** Execute the SQL query and display the books table */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { ResultSet book = getBooks.executeQuery(); ResultSetMetaData rsmd = book.getMetaData(); int numColumns = rsmd.getColumnCount(); out.println( "\n" + "
" + rsmd.getColumnName(col) + " | "); } out.println("
---|
" + book.getString(col) + " | "); } out.println("
A database error occurred
" + "" ); out.close(); } } /** Free database resources and close connection */ public void destroy() { try { getBooks.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }