Working with ResultSets

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 ...

Get MySQL™ and JSP™ Web Applications: Data-Driven Programming Using Tomcat and MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.