smeacham

PreparedStatement Example

Sep 18th, 2012
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. PreparedStatement ps =
  2.     conn.prepareStatement( "SELECT i.*, j.* FROM Omega i, Zappa j WHERE i.name = ? AND j.num = ?" );
  3. try {
  4.     // In the SQL statement being prepared, each question mark is a placeholder
  5.     // that must be replaced with a value you provide through a "set" method invocation.
  6.     // The following two method calls replace the two placeholders; the first is
  7.     // replaced by a string value, and the second by an integer value.
  8.     ps.setString(1, "Poor Yorick");
  9.     ps.setInt(2, 8008);
  10.  
  11.     // The ResultSet, rs, conveys the result of executing the SQL statement.
  12.     // Each time you call rs.next(), an internal row pointer, or cursor,
  13.     // is advanced to the next row of the result.  The cursor initially is
  14.     // positioned before the first row.
  15.     ResultSet rs = ps.executeQuery();
  16.     try {
  17.         while ( rs.next() ) {
  18.             int numColumns = rs.getMetaData().getColumnCount();
  19.             for ( int i = 1 ; i <= numColumns ; i++ ) {
  20.                 // Column numbers start at 1.
  21.                 // Also there are many methods on the result set to return
  22.                 // the column as a particular type. Refer to the Sun documentation
  23.                 // for the list of valid conversions.
  24.                 System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
  25.             } // for
  26.         } // while
  27.     } finally {
  28.         try { rs.close(); } catch (Throwable ignore) { /* Propagate the original exception
  29. instead of this one that you may want just logged */ }
  30.     }
  31. } finally {
  32.    try { ps.close(); } catch (Throwable ignore) { /* Propagate the original exception
  33. instead of this one that you may want just logged */ }
  34. } // try
Advertisement
Add Comment
Please, Sign In to add comment