COSC 2206 Internet Tools Java Servlets with JDBC and MySQL For complete install instructions  http://www.cs.laurentian.ca/...
JDBC-MySQL driver (1) <ul><li>JDBC (Java DataBase Connector) is a common interface (API) to various relational databases <...
JDBC-MySQL driver (2) <ul><li>Unzip to get a jar file which you can rename to a shorter name such as   mysql-jdbc-driver.j...
JDBC-MySQL driver (3) <ul><li>This gives two ways to compile a Java class that uses the driver:   java -cp CLASSPATH MyCla...
JDBC-MySQL driver (4) <ul><li>When using servlets the tomcat server has its own classpath. In a web applciation called tes...
Database independence MySQL database Oracle database ODBC database Driver Driver Driver DriverManager Connection Statement...
JDBC interface DriverManager Connection Statement PreparedStatement CallableStatement ResultSet ResultSetMetaData RowSet R...
Loading the driver <ul><li>The driver is loaded at runtime using the statement </li></ul><ul><li>A  ClassNotFoundException...
Connecting to database (1) <ul><li>The database, user name and password are specified by a URL-like string such as </li></...
Connecting to database (2) import  java.sql.*; ... try {  Class.forName( &quot;com.mysql.jdbc.Driver&quot; ); } catch  (Cl...
ConnectionTester import  java.sql.*; public class  ConnectionTester {   public static void  main(String[] args)   {   // c...
ConnectionTester if  (args.length == 3)   {   user = args[0];   password = args[1];   database = args[2];   }   else   {  ...
ConnectionTester try   {  Class.forName( &quot;com.mysql.jdbc.Driver&quot; );   Connection conn =    DriverManager.getConn...
ConnectionTester <ul><li>Compile the class using </li></ul><ul><ul><li>javac ConnectionTester </li></ul></ul><ul><li>Run t...
Executing a SELECT query <ul><li>First create a  Statement  object </li></ul><ul><li>Then create a query string. For examp...
Getting query results (1) <ul><li>Column names and number of columns. If  rs  is a  ResultSet  object then number of colum...
Getting query results (2) <ul><li>Iterating over the rows of a table </li></ul>while  (rs.next()) {   for  ( int  i = 1; i...
Executing a simple command <ul><li>First create a Statement object </li></ul><ul><li>Then create a command string. For exa...
The Connection interface <ul><li>Two important methods: </li></ul><ul><li>Statement with no parameters </li></ul><ul><li>S...
Example <ul><li>Make a connection and create a statement </li></ul>Connection conn =    DriverManager.getConnection(url,us...
The Statement interface <ul><li>Execute a command </li></ul><ul><li>Execute a query which returns a result set </li></ul><...
Types of statements <ul><li>A  Statement  object is used to execute a simple SQL statement without parameters </li></ul><u...
Dropping a table <ul><li>Dropping a database table </li></ul><ul><li>Another way </li></ul>PreparedStatement dropTable =  ...
Creating a table <ul><li>Creating a database table </li></ul>PreparedStatement createTable =    connection.prepareStatemen...
books database table (1) CREATE DATABASE IF NOT EXISTS web_db; USE web_db; DROP TABLE IF EXISTS books; CREATE TABLE books ...
books database table (2) INSERT INTO books VALUES (   '0-672-31784-2',   'PHP and MySQL Web Development',   'Luke Welling,...
MySQLTester.java import  java.sql.*; public class  MySQLTester {   private  String host =  &quot;localhost&quot; ;   priva...
MySQLTester.java public void  run(String user, String password,   String database, String query)   {   try   {   Class.for...
MySQLTester.java try   {   Connection conn = DriverManager.getConnection(   &quot;jdbc:mysql://&quot;  + host +  &quot;:&q...
MySQLTester.java // Get number of columns in table   ResultSetMetaData rsmd = rs.getMetaData();   int numberOfColumns = rs...
MySQLTester.java // Use ResultSet iterator to display table   // columns   while  (rs.next())   {   for  ( int  i = 1; i <...
MySQLTester.java rs.close();   conn.close();   }   catch (SQLException e)   {   System.out.println(e.getMessage());   Syst...
DBaseTestServlet.java (1) package  dbase; import  java.io.*; import  java.sql.*; import  java.servlet.*; import  java.serv...
DBaseTestServlet.java (2) try   {    Class.forName( &quot;com.mysql.jdbc.Driver&quot; );   connection = DriverManager.getC...
DBaseTestServlet.java (3) public void  doGet(HttpServletRequest request,   HttpServlet response) throws IOException,   Ser...
DBaseTestServlet.java (4) st.execute(   &quot;INSERT INTO test VALUES ('Fred', 34)&quot; );   ResultSet rs = st.executeQue...
DBaseTestServlet.java (5) out.println( &quot;<html>
&quot;   +  &quot;<head><title>Testing JDBC</title></head>
&quot;   + ...
DBaseTestServlet.java (6) public void  destroy()   {  try   {   connection.close();   }   catch  (SQLException e)   {   e....
BookDisplayServlet0 (1) package  dbase; import  java.io.*; import  java.sql.*; import  javax.servlet.*; import  javax.serv...
BookDisplayServlet0 (2) public void  init()  throws  ServletException   {   try   {    Class.forName( &quot;com.mysql.jdbc...
BookDisplayServlet0 (3) getBooks = connection.prepareStatement(   &quot;SELECT * FROM books&quot; );   }   catch (Exceptio...
BookDisplayServlet0 (4) public void  doGet(HttpServletRequest request,    HttpServletResponse response)   throws  IOExcept...
BookDisplayServlet0 (5) try   {   ResultSet book = getBooks.executeQuery();   ResultSetMetaData rsmd = book.getMetaData();...
BookDisplayServlet0 (6) // display column names   out.println( &quot;<tr>&quot; );   for  ( int  col = 1; col <= numColumn...
BookDisplayServlet0 (7) // Display rows of table   while (book.next())   {   out.println( &quot;<tr>&quot; );   for  ( int...
BookDisplayServlet0 (8) catch  (SQLException e)   {   e.printStackTrace();   out.println(   &quot;<html>
&quot;   +  &quot...
BookDisplayServlet0 (9) public void  destroy()   {   try   {   getBooks.close();   connection.close();   }   catch  (SQLEx...
Using web.xml (1) <ul><li>Constants can be stored here to specify database parameters: </li></ul><context-param>   <param-...
Using web.xml (2) <context-path>   <param-name> jdbc.username </param-name>   <param-value> uuuuu </param-value> </contex-...
SQLTestServlet output (1) SELECT * FROM ages DROP TABLE IF EXISTS ages; CREATE TABLE ages ( ID INT(10) NOT NULL AUTO_INCRE...
SQLTestServlet output (2) DELETE FROM ages WHERE ID < 3 SELECT * FROM ages
SQLTestServlet output (3) UPDATE ages SET Age='99' WHERE ID=6 SELECT * FROM ages
SQLTestServlet.java (1) package  dbase; import  java.io.*; import  java.sql.*; import  javax.servlet.*; import  javax.serv...
SQLTestServlet.java (2) public void  init()  throws  ServletException   {    // get database parameters from web.xml Servl...
SQLTestServlet.java (3) try   {   // Load driver and make a connection to the    // java_db database   Class.forName(drive...
SQLTestServlet.java (4) // Define all the SQL commands and queries   dropTable = connection.prepareStatement(   &quot;DROP...
SQLTestServlet.java (5) insertRow = connection.prepareStatement(   &quot;INSERT INTO &quot;  + table +  &quot;(Name, Age)&...
SQLTestServlet.java (6) catch  (Exception e)   {   e.printStackTrace();   throw new  UnavailableException(   e.getMessage(...
SQLTestServlet.java (7) public void  doGet(HttpServletRequest request,    HttpServletResponse response)   throws  IOExcept...
SQLTestServlet.java (8) try   {  // create the database table   dropTable.execute();   createTable.execute();   // Insert ...
SQLTestServlet.java (9) out.println(   &quot; <h1>Initial database table</h1>&quot; );   displayTable(out);   // Delete en...
SQLTestServlet.java (10) // Update a table row   updateRow.executeUpdate();   out.println( &quot;<h1>After update ...</h1>...
SQLTestServlet.java (11) public void  displayTable(PrintWriter out)   throws  SQLException   {   Statement st = connection...
SQLTestServlet.java (12) // display column headings   out.println( &quot;<tr>&quot; );   for  ( int  col= 1; col <= numCol...
SQLTestServlet.java (13) // display table rows   while  (result.next())   {   out.println( &quot;<tr>&quot; );   for  ( in...
SQLTestServlet.java (14) public void  destroy()   {  try   {   connection.close();   dropTable.close();   createTable.clos...
BookDisplayServlet1 The following version uses web.xml to store the database parameters so that they are not &quot;wired-i...
BookDisplayServlet1 (1) package  dbase; import  java.io.*; import  java.sql.*; import  javax.servlet.*; import  javax.serv...
BookDisplayServlet1 (2) public void  init()  throws  ServletException   {   // Get the jdbc connection parameters from the...
BookDisplayServlet1 (3) try   {  Class.forName(driver);   connection =    DriverManager.getConnection(url,user,pass);   ge...
BookDisplayServlet1 (4) public void  doGet(HttpServletRequest request,    HttpServletResponse response)   throws  IOExcept...
BookDisplayServlet1 (5) try   {   ResultSet book = getBooks.executeQuery();   ResultSetMetaData rsmd = book.getMetaData();...
BookDisplayServlet1 (6) // display column names   out.println( &quot;<tr>&quot; );   for  ( int  col = 1; col <= numColumn...
BookDisplayServlet1 (7) // Display rows of table   while (book.next())   {   out.println( &quot;<tr>&quot; );   for  ( int...
BookDisplayServlet1 (8) catch  (SQLException e)   {   e.printStackTrace();   out.println(   &quot;<html>
&quot;   +  &quot...
BookDisplayServlet1 (9) public void  destroy()   {   try   {   getBooks.close();   connection.close();   }   catch  (SQLEx...
Beans Version Beans version of the Book display servlet
BookDisplayServlet (1) package  dbase; import  java.io.*; import  java.sql.*; import  javax.servlet.*; import  javax.servl...
BookDisplayServlet (2) public void  init()  throws  ServletException   {   // Get the jdbc connection parameters from the ...
BookDisplayServlet (3) try   {   DBConnectorBean =  new  DBConnectorBean();   db.setDriver(driver);   db.setUrl(url);   db...
BookDisplayServlet (4) public void  doGet(HttpServletRequest request,    HttpServletResponse response)   throws  IOExcepti...
BookDisplayServlet (5) out.println(   &quot;<html>
&quot;   +  &quot;<head><title>...</title></head>
&quot;   +  &quot;<bo...
BookDisplayServlet (6) Iterator bookListIterator =   bookDataBean.getIterator();   BookBean book;   while  (bookListIterat...
BookDisplayServlet (7) public void  destroy()   {   bookDataBean.destroy(); } }  // end of servlet
BookBean (1) package  beans; public class  BookBean  implements  java.io.Serializable {   // instance datafields are calle...
BookBean (2) public void  setIsbn(String isbn)   {  this .isbn = isbn; }   public void  setTitle(String title)   {  this ....
DBConnectorBean (1) package  beans; import  java.sql.*; public class  DBConnectorBean implements   java.io.Serializable { ...
DBConnectorBean (2) public void  setUrl(String url)   {  theUrl = url; }   public void  setUsername(String username)   {  ...
BookDataBean (1) package  beans; import  java.sql.*; import  java.util.*: import  beans.BookBean; public class  BookDataBe...
BookDataBean (2) public  Iterator getIterator()   {   List bookList =  new  ArrayList();   try   {   getBooks = connection...
BookDataBean (3) book.setYear(results.getString(5));   book.setPrice(results.getDouble(6));   bookList.add(book);   }   } ...
BookDataBean (4) public void  destroy()   {   try   {   getBooks.close();   connection.close();   }   catch  (SQLException...
Upcoming SlideShare
Loading in...5
×

jdbc.ppt

1,474

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,474
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
149
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "jdbc.ppt"

  1. 1. COSC 2206 Internet Tools Java Servlets with JDBC and MySQL For complete install instructions http://www.cs.laurentian.ca/badams/c2206
  2. 2. JDBC-MySQL driver (1) <ul><li>JDBC (Java DataBase Connector) is a common interface (API) to various relational databases </li></ul><ul><li>We will use the JDBC-MySQL driver that can be obtained from the MySQL web site </li></ul><ul><ul><li>www.mysql.com </li></ul></ul><ul><li>Download the file </li></ul><ul><ul><li>mysql-connector-java-3.0.14-production.zip </li></ul></ul>
  3. 3. JDBC-MySQL driver (2) <ul><li>Unzip to get a jar file which you can rename to a shorter name such as mysql-jdbc-driver.jar </li></ul><ul><li>There is also an unjarred version in the com directory: the full name of the driver is </li></ul><ul><ul><li>com.mysql.jdbc.Driver </li></ul></ul><ul><li>Put the com directory and the jar file in your packages directory (e.g., c:packages ) for use in stand-alone java applications </li></ul>
  4. 4. JDBC-MySQL driver (3) <ul><li>This gives two ways to compile a Java class that uses the driver: java -cp CLASSPATH MyClass where CLASSPATH is </li></ul><ul><ul><li>.;c:packages;c:packagesmysql-jdbc-driver.jar </li></ul></ul><ul><ul><li>.;c:packages </li></ul></ul><ul><li>The first uses the jar file and the second uses the unpacked com directory. </li></ul>
  5. 5. JDBC-MySQL driver (4) <ul><li>When using servlets the tomcat server has its own classpath. In a web applciation called test the driver file mysql-jdbc-driver.jar must go in the directory c: omcatwebapps estWEB-INFlib </li></ul><ul><li>To make it available to all web applications put it in directory c: omcatcommonlib </li></ul><ul><li>We won't need to do this. </li></ul><ul><li>See JDBC install instructions for all details </li></ul>
  6. 6. Database independence MySQL database Oracle database ODBC database Driver Driver Driver DriverManager Connection Statement PreparedStatement ResultSet ResultSet
  7. 7. JDBC interface DriverManager Connection Statement PreparedStatement CallableStatement ResultSet ResultSetMetaData RowSet RowSetMetaData Class Interface
  8. 8. Loading the driver <ul><li>The driver is loaded at runtime using the statement </li></ul><ul><li>A ClassNotFoundException can be thrown </li></ul><ul><li>Note that the Java compiler doesn't need to know the classpath to the driver since it is loaded at runtime by the Java interpreter. </li></ul>Class.forName( &quot;com.mysql.jdbc.Driver&quot; );
  9. 9. Connecting to database (1) <ul><li>The database, user name and password are specified by a URL-like string such as </li></ul><ul><li>Parts of string can be specified by variables </li></ul><ul><li>Now connect using </li></ul>String dsn = &quot;jdbc:mysql://localhost:3306/ myDatabase?user=myUserName&password=myPassword&quot; ; String dsn = &quot; jdbc:mysql://&quot; + host + &quot;:&quot; + port + &quot;/&quot; + database + &quot;?user=&quot; + user + &quot;&password=&quot; + password; Connection conn = DriverManager.getConnection(dsn);
  10. 10. Connecting to database (2) import java.sql.*; ... try { Class.forName( &quot;com.mysql.jdbc.Driver&quot; ); } catch (ClassNotFoundException e) {...} try { Connection conn = DriverManager.getConnection(dsn); } catch (SQLException e) {...}
  11. 11. ConnectionTester import java.sql.*; public class ConnectionTester { public static void main(String[] args) { // connection parameters String host = &quot;localhost&quot; ; String port = &quot;3306&quot; ; String user = &quot;&quot; ; String password = &quot;&quot; ; String database = &quot;&quot; ; See jdbc install notes (html)
  12. 12. ConnectionTester if (args.length == 3) { user = args[0]; password = args[1]; database = args[2]; } else { System.out.println( &quot;args: user password database&quot; ); System.exit(0); }
  13. 13. ConnectionTester try { Class.forName( &quot;com.mysql.jdbc.Driver&quot; ); Connection conn = DriverManager.getConnection( &quot;jdbc:mysql://&quot; + host + &quot;:&quot; + port + &quot;/&quot; + database + &quot;?user=&quot; + user + &quot;&password=&quot; + password); conn.close(); } catch (ClassNotFoundException e) {...} catch (SQLException e) {...} System.out.println( &quot;Connection success&quot; ); } } ConnectionTester.java
  14. 14. ConnectionTester <ul><li>Compile the class using </li></ul><ul><ul><li>javac ConnectionTester </li></ul></ul><ul><li>Run the class using </li></ul><ul><ul><li>java -cp .;c:packages ConnectionTester user password web_db </li></ul></ul><ul><li>Replace user and password with your values </li></ul><ul><li>Replace web_db with your database </li></ul>
  15. 15. Executing a SELECT query <ul><li>First create a Statement object </li></ul><ul><li>Then create a query string. For example </li></ul><ul><li>Execute the query </li></ul><ul><li>The ResultSet object returned contains the results of the query. </li></ul>Statement stmt = conn.createStatement(); String query = &quot;SELECT * FROM table&quot; ; ResultSet rs = stmt.executeQuery(query);
  16. 16. Getting query results (1) <ul><li>Column names and number of columns. If rs is a ResultSet object then number of columns in table is </li></ul><ul><li>The name of column i ( i =1,2,3,...) is </li></ul>ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); String colName = rsmd.getColumnName(i)
  17. 17. Getting query results (2) <ul><li>Iterating over the rows of a table </li></ul>while (rs.next()) { for ( int i = 1; i <= numberOfColumns; i++) { String columnValue = rs.getString(i); // do something with columnValue } } There are lots of get methods for retriving column values as integers, doubles, etc.
  18. 18. Executing a simple command <ul><li>First create a Statement object </li></ul><ul><li>Then create a command string. For example </li></ul><ul><li>Execute the command </li></ul>Statement stmt = conn.createStatement(); String cmd = &quot;DROP TABLE IF EXISTS test&quot; ; stmt.execute(cmd);
  19. 19. The Connection interface <ul><li>Two important methods: </li></ul><ul><li>Statement with no parameters </li></ul><ul><li>Statement with parameters </li></ul><ul><li>PreparedStatement is a subinterface of Statement </li></ul>public Statement createStatement() public PreparedStatement prepareStatement()
  20. 20. Example <ul><li>Make a connection and create a statement </li></ul>Connection conn = DriverManager.getConnection(url,user,pass); Statement st = conn.createStatement();
  21. 21. The Statement interface <ul><li>Execute a command </li></ul><ul><li>Execute a query which returns a result set </li></ul><ul><li>Execute an update, insert, or delete SQL statement </li></ul><ul><li>Many other methods </li></ul>boolean execute(String sql) ResultSet executeQuery(String sql) int executeUpdate(String sql)
  22. 22. Types of statements <ul><li>A Statement object is used to execute a simple SQL statement without parameters </li></ul><ul><li>A PreparedStatement object is used to execute a precompiled SQL statement with or without IN parameters </li></ul><ul><li>There are also CallableStatement objects for OUT parameters (uses stored procedures in the database) </li></ul>
  23. 23. Dropping a table <ul><li>Dropping a database table </li></ul><ul><li>Another way </li></ul>PreparedStatement dropTable = connection.prepareStatement( &quot;DROP TABLE IF EXISTS ages&quot;); ... dropTable.execute(); Statement dropTable = connection.createStatement( &quot;DROP TABLE IF EXISTS ages&quot;); dropTable.execute();
  24. 24. Creating a table <ul><li>Creating a database table </li></ul>PreparedStatement createTable = connection.prepareStatement( &quot;CREATE TABLE ages (&quot; + &quot;ID INT(10) NOT NULL AUTO_INCREMEMT, &quot; + &quot;Name VARCHAR(12), &quot; + &quot;Age INT, &quot; + &quot;PRIMARY KEY(ID)&quot; + &quot;)&quot; ); ... createTable.execute();
  25. 25. books database table (1) CREATE DATABASE IF NOT EXISTS web_db; USE web_db; DROP TABLE IF EXISTS books; 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 );
  26. 26. books database table (2) INSERT INTO books VALUES ( '0-672-31784-2', 'PHP and MySQL Web Development', 'Luke Welling, Laura Thomson', 'Sams', 2001, 74.95 ); ............ INSERT INTO books VALUES ( '1-56592-243-3', 'Perl Cookbook', 'Tom Christianson, Nathan Torkington', 'O'Reilly', 1999, 56.95 );
  27. 27. MySQLTester.java import java.sql.*; public class MySQLTester { private String host = &quot;localhost&quot; ; private String port = &quot;3306&quot; ; public static void main(String[] args) { MySQLTester prog = new MySQLTester(); if (args.length == 4) prog.run(args[0], args[1], args[2], args[3]); else System.out.println( &quot;Args: user password database &quot;query&quot;&quot; ); } See jdbc install notes (html)
  28. 28. MySQLTester.java public void run(String user, String password, String database, String query) { try { Class.forName( &quot;com.mysql.jdbc.Driver&quot; ); } catch (ClassNotFoundException e) { System.out.println( &quot;Could not find driver&quot; ); System.exit(0); }
  29. 29. MySQLTester.java try { Connection conn = DriverManager.getConnection( &quot;jdbc:mysql://&quot; + host + &quot;:&quot; + port + &quot;/&quot; + database + &quot;?user=&quot; + user + &quot;&password=&quot; + password); // Execute a query and get resulting table Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query);
  30. 30. MySQLTester.java // Get number of columns in table ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); // Simple display of column names for ( int i = 1; i <= numberOfColumns, i++) { System.out.print(rsmd.GetColumnName(i)); if (i < numberOfColumns) System.out.print( &quot;:&quot; ); // separator } System.out.println();
  31. 31. MySQLTester.java // Use ResultSet iterator to display table // columns while (rs.next()) { for ( int i = 1; i <= numberOfColumns; i++) { String columnValue = rs.getString(i); System.out.println(columnValue); if (i < numberOfColumns) System.out.print( &quot;:&quot; ); } System.out.println(); }
  32. 32. MySQLTester.java rs.close(); conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); System.exit(); } } } Compile it and run it using the command java -cp .;c:packagemysql-jdbc-driver.jar MySQLTester user password web_db &quot;SELECT * FROM books&quot; MySQLTester.java (see install notes)
  33. 33. DBaseTestServlet.java (1) package dbase; import java.io.*; import java.sql.*; import java.servlet.*; import java.servlet.http.*; public class DBaseTestServlet extends HttpServlet { private Connection connection; public void init() throws ServletException { DBaseTestServlet.java This servlet is part of the install instructions and is available in the test webapp as dbase.DBaseTestServlet See jdbc install notes (html)
  34. 34. DBaseTestServlet.java (2) try { Class.forName( &quot;com.mysql.jdbc.Driver&quot; ); connection = DriverManager.getConnection( &quot;jdbc:mysql&quot;//localhost:3306/web_db&quot; , &quot;user&quot; , &quot;password&quot; ); } catch (ClassNotFoundException e) { ... } catch (SQLException e) { ... } } There is a better way
  35. 35. DBaseTestServlet.java (3) public void doGet(HttpServletRequest request, HttpServlet response) throws IOException, ServletException { String name = &quot;&quot; ; int age = 0; response.setContentType( &quot;text/html&quot; ); PrintWriter out = response.getWriter(); try { Statement st = connection.createStatement(): st.execute( &quot;DROP TABLE IF EXISTS test&quot; ); st.execute( &quot;CREATE TABLE test (&quot; + &quot;name VARCHAR(20) NOT NULL,&quot; + &quot;age INTEGER NOT NULL )&quot; );
  36. 36. DBaseTestServlet.java (4) st.execute( &quot;INSERT INTO test VALUES ('Fred', 34)&quot; ); ResultSet rs = st.executeQuery( &quot;SELECT * FROM test&quot; ); result.next(); // only one row name = result.getString( &quot;name&quot; ); age = result.getInt( &quot;age&quot; ); st.execute( &quot;DROP TABLE test&quot; ); } catch (SQLException e) { System.out.println( &quot;Error in statement&quot; ); }
  37. 37. DBaseTestServlet.java (5) out.println( &quot;<html> &quot; + &quot;<head><title>Testing JDBC</title></head> &quot; + &quot;<body> &quot; + &quot;The name is &quot; + name + &quot;<br />&quot; + &quot;The age is &quot; + age + &quot;</body> &quot; + &quot;</html> &quot; ); } // end of doGet
  38. 38. DBaseTestServlet.java (6) public void destroy() { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // end servlet
  39. 39. BookDisplayServlet0 (1) package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class BookDisplayServlet0 extends HttpServlet { private Connection connection; private PreparedStatement getBooks; This servlet is part of the install instructions and is available in the test webapp as dbase.BookDisplayServlet0 See jdbc install notes (html)
  40. 40. BookDisplayServlet0 (2) public void init() throws ServletException { try { Class.forName( &quot;com.mysql.jdbc.Driver&quot; ); connection = DriverManager.getConnection( &quot;jdbc:mysql://localhost:3306/bookstore&quot; , &quot;user&quot; , &quot;password&quot; ); the three argument form of the getConnection method
  41. 41. BookDisplayServlet0 (3) getBooks = connection.prepareStatement( &quot;SELECT * FROM books&quot; ); } catch (Exception e) { e.printStackTrace(); throw new UnavailableException(e.getMessage()); } } // end init method
  42. 42. BookDisplayServlet0 (4) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType( &quot;text/html&quot; ); PrintWriter out = response.getWriter();
  43. 43. BookDisplayServlet0 (5) try { ResultSet book = getBooks.executeQuery(); ResultSetMetaData rsmd = book.getMetaData(); int numColumns = rsmd.getColumnCount(); out.println( &quot;<html> &quot; + &quot;<head><title>Displaying the books database table</title></head> &quot; + &quot;<body> &quot; + &quot;<h1>Displaying the books database table</h1> &quot; + &quot;<table border=&quot;1&quot;>&quot; );
  44. 44. BookDisplayServlet0 (6) // display column names out.println( &quot;<tr>&quot; ); for ( int col = 1; col <= numColumns; col++) { out.println( &quot;<th>&quot; + rsmd.getColumnName(col) + &quot;</th>&quot; ); } out.println( &quot;</tr>&quot; );
  45. 45. BookDisplayServlet0 (7) // Display rows of table while (book.next()) { out.println( &quot;<tr>&quot; ); for ( int col = 1; col <= numColumns;col++) { out.println( &quot;<td>&quot; + book.getString(col) + &quot;</td>&quot; ); } out.println( &quot;</tr>&quot; ); } out.println( &quot;</table> </html>&quot; ); out.close(); } // end try
  46. 46. BookDisplayServlet0 (8) catch (SQLException e) { e.printStackTrace(); out.println( &quot;<html> &quot; + &quot;<head><title>SQL Error</title></head> &quot; + &quot;<body> &quot; + &quot;<h1>SQL Error</h1> &quot; + &quot;<p>A database error occurred</p>&quot; + &quot;</body></html>&quot; ); out.close(); } } // end doGet
  47. 47. BookDisplayServlet0 (9) public void destroy() { try { getBooks.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // end BookDisplayServlet0
  48. 48. Using web.xml (1) <ul><li>Constants can be stored here to specify database parameters: </li></ul><context-param> <param-name> jdbc.driver </param-name> <param-value> com.mysql.jdbc.Driver </param-value> </context-param> <context-param> <param-name> jdbc.url </param-name> <param-value> jdbc:mysql://localhost:3306/web_db </param-value> </context-param>
  49. 49. Using web.xml (2) <context-path> <param-name> jdbc.username </param-name> <param-value> uuuuu </param-value> </contex-path> <context-path> <param-name> jdbc.password </param-name> <param-value>ppppp</param-value> </context-path> The next example, SQLTestServlet , shows how to read these values using the ServletContext
  50. 50. SQLTestServlet output (1) SELECT * FROM ages DROP TABLE IF EXISTS ages; CREATE TABLE ages ( ID INT(10) NOT NULL AUTO_INCREMENT, Name VARCHAR(12), AGE INT, PRIMARY KEY(ID) ); INSERT INTO ages (Name,Age) VALUES (?,?);
  51. 51. SQLTestServlet output (2) DELETE FROM ages WHERE ID < 3 SELECT * FROM ages
  52. 52. SQLTestServlet output (3) UPDATE ages SET Age='99' WHERE ID=6 SELECT * FROM ages
  53. 53. SQLTestServlet.java (1) package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class SQLTestServlet extends HttpServlet { private Connection connection; private PreparedStatement dropTable; private PreparedStatement createTable; private PreparedStatement insertRow; private PreparedStatement deleteRows; private PreparedStatement updateRow; private String table = &quot;ages&quot; ; See the c2206 web app servlet dbase.SQLTestServlet
  54. 54. SQLTestServlet.java (2) public void init() throws ServletException { // get database parameters from web.xml ServletContext context = getServletContext(); String driver = context.getInitParameter( &quot;jdbc.driver&quot; ); String url = context.getInitParameter( &quot;jdbc.url&quot; ); String user = context.getInitParameter( &quot;jdbc.username&quot; ); String pass = context.getInitParameter( &quot;jdbc.password&quot; );
  55. 55. SQLTestServlet.java (3) try { // Load driver and make a connection to the // java_db database Class.forName(driver); connection = DriverManager.getConnection(url, user, pass);
  56. 56. SQLTestServlet.java (4) // Define all the SQL commands and queries dropTable = connection.prepareStatement( &quot;DROP TABLE IF EXISTS &quot; + table ); createTable = connection.prepareStatement( &quot;CREATE TABLE &quot; + table + &quot;(&quot; + &quot;ID INT(10) NOT NULL AUTO_INCREMENT, &quot; + &quot;Name VARCHAR(12), &quot; + &quot;Age INT, &quot; + &quot;PRIMARY KEY(ID)&quot; + &quot;)&quot; );
  57. 57. SQLTestServlet.java (5) insertRow = connection.prepareStatement( &quot;INSERT INTO &quot; + table + &quot;(Name, Age)&quot; &quot;VALUES (?,?)&quot; ); deleteRows = connection.prepareStatement( &quot;DELETE FROM &quot; + table + &quot; WHERE ID < 3&quot; ); updateRow = connection.prepareStatement( &quot;UPDATE &quot; + table + &quot; SET Age='99' WHERE ID=6&quot; ); } // end try
  58. 58. SQLTestServlet.java (6) catch (Exception e) { e.printStackTrace(); throw new UnavailableException( e.getMessage()); } } // end init
  59. 59. SQLTestServlet.java (7) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType( &quot;text/html&quot; ); PrintWriter out = response.getWriter(); out.println( &quot;<html> &quot; + &quot;<head><title>Database operations&quot; + &quot;</title></head> &quot; + &quot;<body> &quot; );
  60. 60. SQLTestServlet.java (8) try { // create the database table dropTable.execute(); createTable.execute(); // Insert a few rows and display table String[] names = { &quot;Fred&quot; , &quot;Gord&quot; , &quot;Alice&quot; , &quot;Bob&quot; , &quot;Barney&quot; , &quot;Wilma&quot; }; int[] ages = {37,23,17,23,35,33}; for ( int k = 0; k < ages.length; k++) { insertRow.setString(1, names[k]); insertRow.setInt(2, ages[k]); insertRow.executeUpdate(); }
  61. 61. SQLTestServlet.java (9) out.println( &quot; <h1>Initial database table</h1>&quot; ); displayTable(out); // Delete entries with ID < 3 and display deleteRows.execute(); out.println( &quot;<h1>Table with rows deleted</h1>&quot; ); displayTable(out);
  62. 62. SQLTestServlet.java (10) // Update a table row updateRow.executeUpdate(); out.println( &quot;<h1>After update ...</h1>&quot; ); displayTable(out); out.println( &quot;<body> </html>&quot; ); } catch (SQLException e) { e.printStackeTrace(); } } // end doGet
  63. 63. SQLTestServlet.java (11) public void displayTable(PrintWriter out) throws SQLException { Statement st = connection.createStatement(); ResultSet result = st.executeQuery( &quot;SELECT * FROM &quot; + table); ResultSetMetaData rsmd = result.getMetaData(); int numColumns = rsmd.getColumnCount(); // begin the HTML table out.println( &quot;<table border=&quot;1&quot; cellpadding=&quot;3&quot;>&quot; );
  64. 64. SQLTestServlet.java (12) // display column headings out.println( &quot;<tr>&quot; ); for ( int col= 1; col <= numColumns; col++) { out.println( &quot;<th>&quot; + rsmd.getColumnName(col) + &quot;</th>&quot; ); } out.println( &quot;</tr>&quot; );
  65. 65. SQLTestServlet.java (13) // display table rows while (result.next()) { out.println( &quot;<tr>&quot; ); for ( int col = 1; col <= numColumns; col++) { out.println( &quot;<td>&quot; + result.getString(col) + &quot;</td>&quot; ); } out.println( &quot;</tr>&quot; ); } out.println( &quot;</table>&quot; ); result.close(); } // end displayTable
  66. 66. SQLTestServlet.java (14) public void destroy() { try { connection.close(); dropTable.close(); createTable.close(); insertRow.close(); deleteRows.close(); updateRow.close(); } catch (SQLException e) { e.printStackTrace(); } } // end destroy } // end SQLTestServlet
  67. 67. BookDisplayServlet1 The following version uses web.xml to store the database parameters so that they are not &quot;wired-in&quot; to the class. See the c2206 web app servlet dbase.BookDisplayServlet1
  68. 68. BookDisplayServlet1 (1) package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class BookDisplayServlet1 extends HttpServlet { private Connection connection; private PreparedStatement getBooks;
  69. 69. BookDisplayServlet1 (2) public void init() throws ServletException { // Get the jdbc connection parameters from the // web.xml file ServletContext context = getServletContext(); String driver = context.getInitParameter( &quot;jdbc.driver&quot; ); String url = context.getInitParameter( &quot;jdbc.url&quot; ); String user = context.getInitParameter( &quot;jdbc.username&quot; ); String pass = context.getInitParameter( &quot;jdbc.password&quot; );
  70. 70. BookDisplayServlet1 (3) try { Class.forName(driver); connection = DriverManager.getConnection(url,user,pass); getBooks = connection.prepareStatement( &quot;SELECT * FROM books&quot; ); } catch (Exception e) { e.printStackTrace(); throw new UnavailableException(e.getMessage()); } } // end init method
  71. 71. BookDisplayServlet1 (4) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType( &quot;text/html&quot; ); PrintWriter out = response.getWriter();
  72. 72. BookDisplayServlet1 (5) try { ResultSet book = getBooks.executeQuery(); ResultSetMetaData rsmd = book.getMetaData(); int numColumns = rsmd.getColumnCount(); out.println( &quot;<html> &quot; + &quot;<head><title>Displaying the books database table</title></head> &quot; + &quot;<body> &quot; + &quot;<h1>Displaying the books database table</h1> &quot; + &quot;<table border=&quot;1&quot;>&quot; );
  73. 73. BookDisplayServlet1 (6) // display column names out.println( &quot;<tr>&quot; ); for ( int col = 1; col <= numColumns; col++) { out.println( &quot;<th>&quot; + rsmd.getColumnName(col) + &quot;</th>&quot; ); } out.println( &quot;</tr>&quot; );
  74. 74. BookDisplayServlet1 (7) // Display rows of table while (book.next()) { out.println( &quot;<tr>&quot; ); for ( int col = 1; col <= numColumns;col++) { out.println( &quot;<td>&quot; + book.getString(col) + &quot;</td>&quot; ); } out.println( &quot;</tr>&quot; ); } out.println( &quot;</table> </html>&quot; ); out.close(); } // end try
  75. 75. BookDisplayServlet1 (8) catch (SQLException e) { e.printStackTrace(); out.println( &quot;<html> &quot; + &quot;<head><title>SQL Error</title></head> &quot; + &quot;<body> &quot; + &quot;<h1>SQL Error</h1> &quot; + &quot;<p>A database error occurred</p>&quot; + &quot;</body></html>&quot; ); out.close(); } } // end doGet
  76. 76. BookDisplayServlet1 (9) public void destroy() { try { getBooks.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // end BookDisplayServlet1
  77. 77. Beans Version Beans version of the Book display servlet
  78. 78. BookDisplayServlet (1) package dbase; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import beans.BookBean; import beans.BookDataBean; import beans.DBConnectorBean; public class BookDisplayServlet extends HttpServlet { private BookDataBean bookDataBean;
  79. 79. BookDisplayServlet (2) public void init() throws ServletException { // Get the jdbc connection parameters from the // web.xml file ServletContext context = getServletContext(); String driver = context.getInitParameter( &quot;jdbc.driver&quot; ); String url = context.getInitParameter( &quot;jdbc.url&quot; ); String user = context.getInitParameter( &quot;jdbc.username&quot; ); String pass = context.getInitParameter( &quot;jdbc.password&quot; );
  80. 80. BookDisplayServlet (3) try { DBConnectorBean = new DBConnectorBean(); db.setDriver(driver); db.setUrl(url); db.setUserName(username); db.setPassword(password); // pass connection to the bean bookDataBean = new BookDataBean(); bookDataBean.setConnection(db); } } // end init method
  81. 81. BookDisplayServlet (4) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { DecimalFormat cents = new DecimalFormat( &quot;0.00&quot; ); response.setContentType( &quot;text/html&quot; ); PrintWriter out = response.getWriter();
  82. 82. BookDisplayServlet (5) out.println( &quot;<html> &quot; + &quot;<head><title>...</title></head> &quot; + &quot;<body> &quot; + &quot;<h1>...</h1> &quot; + &quot;<table border=&quot;1&quot;>&quot; + &quot;<tr> &quot; + &quot;<th>ISBN</th <th>TITLE</th> &quot; + &quot;<th>AUTHOR</th> <th>PUB</th> &quot; + &quot;<th>YEAR</th? <th>PRICE</th> &quot; + &quot;</tr>&quot; );
  83. 83. BookDisplayServlet (6) Iterator bookListIterator = bookDataBean.getIterator(); BookBean book; while (bookListIterator.hasNext()) { book = (BookBean) bookListIterator.next(); out.println( &quot;<tr> &quot; + &quot;<td>&quot; + book.getIsbn() + &quot;</td>&quot; + &quot;<td>&quot; + book.getTitle() + &quot;</td>&quot; + &quot;<td>&quot; + book.getAuthor() + &quot;</td>&quot; + &quot;<td>&quot; + book.getPub() + &quot;</td>&quot; + &quot;<td>&quot; + book.getYear() + &quot;</td>&quot; + &quot;<td>&quot; + cents.format(book.getPrice()) + &quot;</td></tr>&quot; ); } out.println( &quot;</table></body></html>&quot; ); } out.close();
  84. 84. BookDisplayServlet (7) public void destroy() { bookDataBean.destroy(); } } // end of servlet
  85. 85. BookBean (1) package beans; public class BookBean implements java.io.Serializable { // instance datafields are called properties private String isbn, title, author, pub, year; private double price; public String getIsbn() { return isbn; } public String getTitle() { return title; } public String getAuthor() { return author; } public String getPub() { return pub; } public String getYear() { return year; } public double getPrice() { return price; }
  86. 86. BookBean (2) public void setIsbn(String isbn) { this .isbn = isbn; } public void setTitle(String title) { this .title = title; } public void setAuthor(String author) { this .author = author; } public void setPub(String pub) { this .pub = pub; } public void setYear(String year) { this .year = year; } public void setPrice(double price) { this .price = price; } }
  87. 87. DBConnectorBean (1) package beans; import java.sql.*; public class DBConnectorBean implements java.io.Serializable { private String theUrl; private String theUsername; private String thePassword; public void setDriver(String driver) { try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
  88. 88. DBConnectorBean (2) public void setUrl(String url) { theUrl = url; } public void setUsername(String username) { theUsername = username; } public void setPassword(String password) { thePassword = password; } public Connection getConnection() { Connection conn = null; try { con = DriverManager.getConnection( theUrl, theUserName, thePassword); return null; } catch (SQLException e) {e.printStackTrace();} return null; } }
  89. 89. BookDataBean (1) package beans; import java.sql.*; import java.util.*: import beans.BookBean; public class BookDataBean implements java.io.Serializable { private Connection connection; private PreparedStatement getBooks; public void setDatabase(DBConnectorBean db) { connection = db.getConnection(); }
  90. 90. BookDataBean (2) public Iterator getIterator() { List bookList = new ArrayList(); try { getBooks = connection.preparedStatement( &quot;SELECT * FROM books&quot; ); resultSet results = getBooks.executeQuery(); while (results.next()) { BookBean book = new BookBean(); book.setIsbn(results.getString(1)); book.setTitle(results.getString(2)); book.setAuthor(results.getString(3)); book.setPub(results.getString(4));
  91. 91. BookDataBean (3) book.setYear(results.getString(5)); book.setPrice(results.getDouble(6)); bookList.add(book); } } catch (SQLException e) { System.out.println( &quot;SQL query failed&quot; ); } return bookList.iterator(); }
  92. 92. BookDataBean (4) public void destroy() { try { getBooks.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // end BookDataBean
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×