Java Server Pages: A Code-Intensive Premium Reference- P6

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:10

0
45
lượt xem
6
download

Java Server Pages: A Code-Intensive Premium Reference- P6

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Java Server Pages: A Code-Intensive Premium Reference- P6:Before you begin reading Pure JSP Java Server Pages, you might want to take a look at its basic structure. This should help you outline your reading plan if you choose not to read the text from cover to cover. This introduction gives you an overview of what each chapter covers.

Chủ đề:
Lưu

Nội dung Text: Java Server Pages: A Code-Intensive Premium Reference- P6

  1. import java.io.*; public class SelectDataApp { public SelectDataApp() { } public void selectData() { Connection con = null; try { // Load the Driver class file Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Make a connection to the ODBC datasource Movie Catalog con = DriverManager.getConnection("jdbc:odbc:Movie Catalog", "", ""); // Create the statement Statement statement = con.createStatement(); // Use the created statement to SELECT the DATA // FROM the Titles Table. ResultSet rs = statement.executeQuery("SELECT * " + "FROM Titles"); // Iterate over the ResultSet while ( rs.next() ) { - 51 -
  2. // get the title_name, which is a String System.err.println("Title Name = " + rs.getString("title_name")); // get the rating System.err.println("Title Rating = " + rs.getString("rating")); // get the price System.err.println("Title Price = " + rs.getString("price")); // get the quantity System.err.println("Title Quantity = " + rs.getString("quantity") + "\n"); } // Close the ResultSet rs.close(); System.in.read(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } catch (SQLException sqle) { System.err.println(sqle.getMessage()); } catch (ClassNotFoundException cnfe) { System.err.println(cnfe.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } - 52 -
  3. finally { try { if ( con != null ) { // Close the connection no matter what con.close(); } } catch (SQLException sqle) { System.err.println(sqle.getMessage()); } } } public static void main(String[] args) { SelectDataApp selectDataApp = new SelectDataApp(); selectDataApp.selectData(); } } To execute a query, use the same Statement object as in previous examples. You just call a different method. The method to perform a query is executeQuery(). Its signature is listed here: public ResultSet executeQuery(String sql) throws SQLException It takes a SQL string like the executeUpdate() method. The difference from executeUpdate() is that executeQuery() returns a ResultSet object containing the results of the query. In our example, we passed it the string "SELECT * FROM Titles", which returns a collection of rows resulting from the query. After we have our ResultSet object returned from executeQuery(), we can iterate over it. The following code snippet shows how our example processes the query results: - 53 -
  4. // Iterate over the ResultSet while ( rs.next() ) { // get the title_name, which is a String System.err.println("Title Name = " + rs.getString("title_name")); // get the rating System.err.println("Title Rating = " + rs.getString("rating")); // get the price System.err.println("Title Price = " + rs.getString("price")); // get the quantity System.err.println("Title Quantity = " + rs.getString("quantity") + "\n"); } // Close the ResultSet rs.close(); The first thing you do is call the ResultSet.next() method. This method returns a Boolean value, indicating whether the next row in the set is valid. If it is, we can access that row using the Get accessors provided by the ResultSet object. In our example, we use only the getString() method, but they all function the same except for their return type. They take a string value representing the name of the column in the table and return the type that is part of their method name. For example, getString() returns a java.lang.String and getInt() returns an int. You can continue iterating over the ResultSet until next() returns false; at that point you need to close the ResultSet object. When you execute this application, the results will be similar to the following output: Title Name = The Adventures of Buckaroo Bonzai Title Rating = PG Title Price = 19.95 Title Quantity = 10 Title Name = Saving Private Ryan Title Rating = R Title Price = 19.95 Title Quantity = 12 Title Name = So I Married An Axe Murderer Title Rating = PG Title Price = 19.95 Title Quantity = 15 Title Name = Happy Gilmore Title Rating = PG Title Price = 19.95 Title Quantity = 9 Title Name = High Plains Drifter Title Rating = PG Title Price = 29.95 Title Quantity = 10 - 54 -
  5. Title Name = Cape Fear Title Rating = NR Title Price = 6.99 Title Quantity = 21 Title Name = The Last Emperor Title Rating = PG Title Price = 19.95 Title Quantity = 12 Updating Tables Another SQL command we need to examine is the UPDATE statement. It looks for a matching condition and makes the specified changes if its WHERE clause is true. An example of this would be if you sold seven copies of The Last Emperor. You would need to update its quantity to 5. The example in Listing 4.4 does just that. Listing 4.4: UpdateDataApp.java import java.sql.*; public class UpdateDataApp { public UpdateDataApp() { } public void updateData() { Connection con = null; try { // Load the Driver class file Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Make a connection to the ODBC datasource Movie Catalog con = DriverManager.getConnection("jdbc:odbc:Movie Catalog", - 55 -
  6. "", ""); // Create the statement Statement statement = con.createStatement(); // Use the created statement to UPDATE DATA in // the database tables. // Update the Quantity of "The Last Emperor" statement.executeUpdate("UPDATE Titles " + "SET quantity = 5 " + "WHERE title_name = 'The Last Emperor'"); } catch (SQLException sqle) { System.err.println(sqle.getMessage()); } catch (ClassNotFoundException cnfe) { System.err.println(cnfe.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } finally { try { if ( con != null ) { // Close the connection no matter what - 56 -
  7. con.close(); } } catch (SQLException sqle) { System.err.println(sqle.getMessage()); } } } public static void main(String[] args) { UpdateDataApp updateDataApp = new UpdateDataApp(); updateDataApp.updateData(); } } If you examine Listing 4.4's executeUpdate() method, you will see the appropriate SQL string used to perform the previously mentioned update. Run this application and then run the example from Listing 4.3. You will see the change to the quantity value of The Last Emperor. Deleting Data from a Table The last topic for this section is deleting data from the database. It is not much different from the previous database updating functions, but it does deserve its own section. To delete a row from a table, you again use the executeUpdate() method. The only change will be the SQL statement you pass to it. In this example, we have decided to take Cape Fear off the market. It just doesn't sell as well as it did in previous years. So, we put a SQL string together and substitute it into the executeUpdate() method. The changed call will look something like the following snippet: // Use the created statement to DELETE DATA // FROM the Titles table. statement.executeUpdate("DELETE FROM Titles " + "WHERE title_name = 'Cape Fear'"); After you have run this application, re-run SelectDataApp and you will see that the title Cape Fear is no longer in the database. - 57 -
  8. Using the JDBC in JavaServer Pages Now that we have covered the basics of using the JDBC, let's look at how you can integrate it into a JSP. It is really very simple. Listing 4.5 contains a sample JSP that performs a query on the previously used Titles table. Listing 4.5: JDBCExample.jsp JSP JDBC Example 1
  9. // Use the created statement to SELECT the DATA // FROM the Titles Table. ResultSet rs = statement.executeQuery("SELECT * " + "FROM Titles"); // Iterate over the ResultSet %> TitleRatingPriceQuantity
  10. rs.close(); } catch (IOException ioe) { out.println(ioe.getMessage()); } catch (SQLException sqle) { out.println(sqle.getMessage()); } catch (ClassNotFoundException cnfe) { out.println(cnfe.getMessage()); } catch (Exception e) { out.println(e.getMessage()); } finally { try { if ( con != null ) { // Close the connection no matter what con.close(); } } catch (SQLException sqle) { out.println(sqle.getMessage()); - 60 -
Đồng bộ tài khoản