import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class HelloJDBC extends HttpServlet { boolean exceptionRaised; String exceptionMsg; public void init() throws ServletException { exceptionRaised = false; exceptionMsg = ""; try { Class.forName("com.mysql.jdbc.Driver"); } catch( ClassNotFoundException e ) { exceptionRaised = true; exceptionMsg = "Cannot load MySQL driver: " + e.getMessage(); } } /** * Create a form */ String createForm() { String form=""; String method = "method=post"; String action = "action=HelloJDBC"; String e1 = "Product ID:
"; // String e2 = "Description:
"; String e3 = "Price:
"; String e4 = "
"; form += "
"; form += e1 + e3 + e4; form += "
"; return form; } public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.print( "\n" ); out.print( "Hello JDBC\n" ); if( exceptionRaised ) { out.println( exceptionMsg ); return; } try { String url = "jdbc:mysql:///csun?user=csun&password=abcd"; Connection c = DriverManager.getConnection( url ); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "select * from Products"); while( rs.next() ) { out.println( rs.getString("prod_id") ); out.println( rs.getString("description") ); out.println( rs.getFloat("price") ); out.println( "
" ); } if( request.getParameter("update") != null ) { String id = request.getParameter("pid"); String price = request.getParameter("price"); stmt.executeUpdate( "update Products set price=" + price + " where prod_id='" + id + "'" ); } c.close(); } catch( Exception e ) { exceptionRaised = true; exceptionMsg = e.getMessage(); } if( exceptionRaised ) out.println( exceptionMsg ); out.print( createForm() ); out.print( "" ); } public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doGet(request, response); } } // end of class HelloJDBC