Working with ResultSet s

I l @ ve RuBoard

Working with ResultSet s

When you get a ResultSet back from a query, there are several ways to get at the data inside. You can refer to the columns positionally or by name . Let's look at a few code fragments to demonstrate the difference:

 ResultSet rs = st.executeQuery("SELECT * FROM employees"); while (rs.next()) {    String lname = rs.getString("lname_txt"); } 

This example uses reference by name. You ask for column values by using the name of the column as an argument to the getX method:

 ResultSet rs = st.executeQuery("SELECT lname_txt, fname_txt FROM employees"); while (rs.next()) {    String lname = rs.getString(1); } 

This uses positional reference. The integer argument to getString refers to the position of the column in the list of columns specified in the query, starting with 1 for the first field.

In general, you shouldn't use positional notation with a * column list. You might think that you know the order that the columns will be returned in, but that could change if the scheme is rebuilt or moved to a different database. In fact, it is a good idea to always use a reference by name, even when explicitly listing the columns in the SQL statement. That is because it makes the code clearer ”the getX call has the name of the column that it's fetching rather than an arbitrary index. This also means that if another column is added to the start of the select statement, the getX calls don't all need to be renumbered.

In general, it's a good idea to write your queries to explicitly list the fields that you want to get. You also might run into problems with using name-based reference with certain databases, and it could be a bit slower than using positional reference. However, the clarity and additional protection from changes in the query are often worth it.

In addition to getString , you can use getInt , getFloat , getDate , and getTimestamp (among others). JDBC tries to be smart about type conversions, so if you do a getString on an integer column, you'll get a string containing the printed representation of the column.

I l @ ve RuBoard


MySQL and JSP Web Applications. Data-Driven Programming Using Tomcat and MySQL
MySQL and JSP Web Applications: Data-Driven Programming Using Tomcat and MySQL
ISBN: 0672323095
EAN: 2147483647
Year: 2002
Pages: 203
Authors: James Turner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net