Start learning with our library of video tutorials taught by experts. Get started

Java Database Integration with JDBC

Looping through result sets


From:

Java Database Integration with JDBC

with David Gassner

Video: Looping through result sets

When data is returned from the database server, it's encapsulated within the ResultSet object. The ResultSet has a cursor and in-memory pointer that goes from row to row. When the ResultSet is first returned, the starting cursor position is before the first row of data, that is, it's not pointing to any data at first. You have to explicitly move the cursor to the data in order to read it. The cursor can either be before the first row of data, on a row of data, or after the last row of data.
Expand all | Collapse all
  1. 5m 23s
    1. Welcome
      53s
    2. What you should know before starting this course
      1m 20s
    3. Using the exercise files
      3m 10s
  2. 12m 2s
    1. Testing your Java development environment
      5m 14s
    2. Importing a MySQL database
      5m 1s
    3. Creating a database user in MySQL
      1m 47s
  3. 32m 47s
    1. What is JDBC?
      4m 26s
    2. Choosing a JDBC driver
      6m 46s
    3. Connecting to a MySQL database server
      8m 7s
    4. Connecting to a HyperSQL database file
      6m 23s
    5. Executing a static SQL statement
      7m 5s
  4. 17m 42s
    1. Connecting to multiple databases
      6m 24s
    2. Handling JDBC exceptions
      7m 7s
    3. Closing database resources in Java 7
      4m 11s
  5. 47m 25s
    1. Looping through result sets
      8m 23s
    2. Moving the cursor in scrollable result sets
      5m 51s
    3. Limiting the number of fetched rows
      6m 57s
    4. Filtering data with prepared statements
      6m 58s
    5. Calling stored procedures
      5m 48s
    6. Handling multiple values from stored procedures
      5m 54s
    7. Using generic getter methods in Java SE 7
      7m 34s
  6. 45m 23s
    1. Managing data entities with JavaBean classes
      5m 0s
    2. Retrieving a single row as a JavaBean object
      6m 5s
    3. Inserting rows with prepared statements
      8m 2s
    4. Updating rows with prepared statements
      5m 4s
    5. Deleting rows with prepared statements
      4m 9s
    6. Managing data with updatable result sets
      6m 6s
    7. Using a persistent database connection
      6m 43s
    8. Committing and rolling back transactions
      4m 14s
  7. 9m 35s
    1. Getting the DatabaseMetaData object
      3m 40s
    2. Getting column and data type information
      5m 55s
  8. 50s
    1. Next steps
      50s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Java Database Integration with JDBC
2h 51m Intermediate Nov 28, 2012

Viewers: in countries Watching now:

Whether you're building a web- or desktop-based application with Java SE or Java EE, many Java applications need to integrate data from a relational database. This course describes how to read and manage data from relational databases such as MySQL and SQL Server using the Java Database Connectivity (JDBC) API.

Author David Gassner explains how to choose a JDBC driver and connect to one or more databases. He also provides detailed instructions on reading, selecting, and updating data; calling stored procedures; managing data via JavaBean classes or with prepared statements; and working with metadata.

Topics include:
  • Importing a MySQL database
  • Connecting to databases
  • Handling JDBC exceptions
  • Looping through result sets
  • Limiting the number of fetched rows
  • Filtering data with prepared statements
  • Calling stored procedures
  • Inserting, updating, and deleting rows with prepared statements
  • Using a persistent database connection
  • Committing and rolling back transactions
Subjects:
Developer Databases Programming Languages
Software:
Java
Author:
David Gassner

Looping through result sets

When data is returned from the database server, it's encapsulated within the ResultSet object. The ResultSet has a cursor and in-memory pointer that goes from row to row. When the ResultSet is first returned, the starting cursor position is before the first row of data, that is, it's not pointing to any data at first. You have to explicitly move the cursor to the data in order to read it. The cursor can either be before the first row of data, on a row of data, or after the last row of data.

All ResultSets give you the ability to move the cursor forward, so the cursor starts before the first row, and the first thing you need to do is move it to the first row. If you're working with a scrollable ResultSet, you can explicitly move to a particular row, but if you're working with what's called a forward only ResultSet, that is a result set where the cursor can only move forward, then you move the cursor one row at a time by calling a method called Next. The Next method returns a Boolean value. When you call it, if it succeeds in moving the cursor to a row that has data, it returns true, and if it moves toward the row that doesn't have any data that would be after the last row, then it returns false.

And so, when working with a forward only cursor, the most common approach is to use a while loop. Within the conditional block for the while loop, you call the Next method. And if it returns true, you know you're on a row that has data, and you process the data. And if it returns false, then you know you have gone passed the available data, and you can exit the while loop and continue executing your program. Within the while loop, while the cursor is on a row with data, you call various methods to retrieve the data. If a particular column has string values, you can call a method called getString.

You can pass in either the name of the column as a string if you know it or the position of the column as an integer and the position start numbering at one. So let's take a look at some code. I'm working in a project called LoopingRows. In this project, Main method, I'm executing a query to retrieve all data from a table named Tours. Let's take a look at the structure of the Tours table. The Tours table has a number of columns. There is a primary key called tourId, a foreign key called packageId, a number of string columns, including tourName, blurb, description, and so on.

A double-column called price, an integer column called length, and many others. I'm going to write some code that assumes that we're getting back a record set based on the structure of this table, and it's going to loop through the rows that are returned and output some content for each row. I will go to Eclipse. Now I'm not going to put all of this output code in the Main method. Instead, I'm going to create a Utility class that I can call from anywhere in my application. I'll go to my DBPackage, and I'm going to create a sub package.

I'll right-click and choose New > Package, and I'll name my new package Tables. This new package eventually would contain one class for each table in my database. So I have created a new package, and now I'll create a new class for that table. I'll right-click and choose New > Class, and I'll name my class the same as the table, Tours. This is going to be Utility class. It won't be the start up class of my application, so I won't include a Main method, and I'll click Finish. Now I'm going to create static methods to process data. Within the class, I'll create a new public static void method, so I'll put in those keywords, and I'll call my method displayData.

I'll set this method up to receive a single argument, data typed as a JDBC ResultSet. I'll type in ResultSet, press Ctrl+Space, and choose ResultSet from java.sql, I'll name this argument rs, and I'll create the code block. Now, for the purpose of this exercise, I'm going to assume that the cursor is starting before the first row. I could add some additional code to make sure of that, but for the way I'm going to use this code in this application, I'm going to know where the cursor is. So I'm going to start with a while loop. I'll type in while, and I'll choose a while loop with a condition.

For the condition, I'll make it call to rs.next. So now as long as there's available data, I'll just keep on looping. I'm going to collect data from a number of columns and append it altogether to create a string for display. For this purpose I'll use a string buffer, I'll name this object simply buffer. And I'll instantiate it with the class's constructor. I'll expand my editor to full screen so I can see everything I'm typing. Now I'm going to get the current row number and append that as the tour number.

I'll use buffer.append, and I'll first add in a label of the Tour space then I'll append to that the value of rs.getRow. Now this is not a static value. The number will be whatever is first in this record set, and so if you re-sort the data, in some way these values won't stick with the data. If you prefer, you could instead call getInt and pass in either the name or the column index of the column containing the primary key value. So for example, I could instead pass in getInt("tourId").

So, after I have appended the primary key value, I'll then append a colon and a space. Now before we add more content, let's see how we're doing. I'll add some system output, and I'll output the value of buffer.toString. Notice that there are some warning icons when you call the next method or any of the methods that get data from the record set you might be throwing an SQLException. So I'm going to mark this method with the throws declaration, and indicate that it might throw that exception. I'll save my changes, and I'll go back to the main method.

I'll place the cursor within the try block, and within the try block, I'll call this new static method that I have just created. I'll type in the name of my new class, and I press Ctrl+Space to make sure I have imported the class, and then I'll call the display data method and pass in the ResultSet. I'll save my changes and run the code, and I see that I'm correctly getting back 26 rows of data. So now I'm ready to fill in the rest of my display method. I'll go back to my Utility class, and I'll add some more code. After I have gotten the primary key, the next step will be to output the tour name.

So I'll place the cursor after the call to the append method, and I'll append again. And this time I'll output the value of rs.getString, and I'll pass in the name of the column I'm interested in, tourName. Now the column names are not case-sensitive, and that's true for almost every database you might work with. It's certainly true with the MySQL and HSQLDB. So even though HSQLDB marks these column names as all uppercase and MySQL maintains the column names however you typed them in, you can type them however you like here in your Java code.

Next, I'll get the price of the tour. I'll create a new double variable that I'll name Price, and I'll get its value from rs, and this time I'll call the method getDouble, and I'll pass in the name of the column price. Before I output it, I'd like to format it, so I'll use an instance of the NumberFormat class, I'll type in the name of the class, and import it from java.txt, and I'll name the object nf for NumberFormat, and I'll get its reference by calling the static method, NumberFormat.getCurrencyInstance.

Notice that there are many methods that I could call from the NumberFormat class. This one's going to format the price as a dollar value. Then I'll format the price, I'll create a string called formattedPrice, and I'll get its value from calling the format method of the NumberFormat object with nf.format, and I'll pass in the price. And finally, I'll append that result to the buffer, using buffer.append, and I'll pass in a space and in an opening parenthesis, and then the formattedPrice, and then a closing parenthesis.

I already have my code to output the buffer's value. So I'll save my changes, I'll go back to the main method, and I'll run the code again, and there is the result. I'm looping through the data that's returned from the database, and I'm outputting information from the rows one at a time. When I finished with the last row, the next time I call the next method, it returns false because there is no more data, and I exit the loop, and I'm done. So that's the most classic way of working with data returned from the database. The cursor starts before the first row, you call the Next method and each time it returns true you're on the next row of data.

And you use the various get methods of the ResultSet to get a value from a column and process it in some way.

There are currently no FAQs about Java Database Integration with JDBC.

Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Java Database Integration with JDBC.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked