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

10 281 0
Java Server Pages: A Code-Intensive Premium Reference- P6 pps

Đang tải... (xem toàn văn)

Thông tin tài liệu

- 51 - 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() ) { - 52 - // 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()); } - 53 - 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: - 54 - // 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 - 55 - 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", - 56 - "", ""); // 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 - 57 - 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. - 58 - 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 <HTML> <HEAD> <TITLE>JSP JDBC Example 1</TITLE> </HEAD> <BODY> <! Set the scripting language to java and > <! import the java.sql package > <%@ page language="java" import="java.sql.*" %> <% 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(); - 59 - // Use the created statement to SELECT the DATA // FROM the Titles Table. ResultSet rs = statement.executeQuery("SELECT * " + "FROM Titles"); // Iterate over the ResultSet %> <! Add an HTML table to format the results > <TABLE BORDER="1"> <TR> <TH>Title</TH><TH>Rating</TH><TH>Price</TH><TH>Quantity</TH> <% while ( rs.next() ) { // get the title_name, which is a String out.println("<TR>\n<TD>" + rs.getString("title_name") + "</TD>"); // get the rating out.println("<TD>" + rs.getString("rating") + "</TD>"); // get the price out.println("<TD>" + rs.getString("price") + "</TD>"); // get the quantity out.println("<TD>" + rs.getString("quantity") + "</TD>\n</TR>"); } // Close the ResultSet - 60 - 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()); . 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. UpdateDataApp updateDataApp = new UpdateDataApp(); updateDataApp.updateData(); } } If you examine Listing 4.4 's executeUpdate() method, you will see the appropriate SQL string. System.err.println(sqle.getMessage()); } } } public static void main(String[] args) { SelectDataApp selectDataApp = new SelectDataApp(); selectDataApp.selectData(); } } To execute a query,

Ngày đăng: 03/07/2014, 06:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan