Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Moving the cursor in scrollable result sets

From: Java Database Integration with JDBC

Video: Moving the cursor in scrollable result sets

By default, result sets are forward only, that is, the cursor starts before the first row of data and can only move forward once. But a scrollable ResultSet gives you the ability to move back and forth in the result set as needed. You can make the ResultSet scrollable with most database management systems and different database management systems have different rules. For example, MySQL using the Connector/J returns a result set that scrollable by default. But HSQLDB can do a scrollable ResultSet, but you have to say you want it.

Moving the cursor in scrollable result sets

By default, result sets are forward only, that is, the cursor starts before the first row of data and can only move forward once. But a scrollable ResultSet gives you the ability to move back and forth in the result set as needed. You can make the ResultSet scrollable with most database management systems and different database management systems have different rules. For example, MySQL using the Connector/J returns a result set that scrollable by default. But HSQLDB can do a scrollable ResultSet, but you have to say you want it.

You select the ability to scroll the data set when you create the Statement object. In this code I'm creating the Statement with the CreateStatement method, and I'm passing in a type of TYPE_SCROLL_INSENSITIVE. The ResultSet type can be scrollable or forward only, it can also be READ_ONLY or updatable, and it is possible to have a scrollable ResultSet that also updatable if you combine these properties in the right way. Once you have gotten a scrollable ResultSet into memory you can move the cursor that is the pointer to the current row using these methods, beforeFirst(), and first(), move to the position before the first row, and the first row itself, last(), and afterLast(), do the same thing, but for the end of the table and the absolute method receives an integer argument and moves to that particular row.

As I previously mentioned, your number ResultSet rows starting with 1, not with 0. So if your ResultSet has say 50 rows, they are numbered from 1 to 50, not from 0 to 49. There are also methods that return boolean values that you can use to check the current cursor position. isBeforeFirst(), isFirst(), isLast(), and isAfterLast(), and the ResultSet object has other available methods to manage inserting new data and moving the cursor to particular rows after insertions. Take a look at the documentation for more details about that.

But let's go to the code. I'm working in a project called scrollable. In this version of my application, I'm executing a query that's retrieving data from the state's table. Instead of using an asterisk for the columns, I'm explicitly naming the columns I want retrieved, which is typically a better practice than using the asterisk wildcard. I'll get back to result set with those two columns, and I have created a new class called states that in the db table's package, which has a displayData method, the displayData method is looping through the ResultSet, outputting first the stateId, the abbreviation, and then the stateName.

I'll run the code in its existing state, and I get back the list of States. Now I'm going to demonstrate moving the cursor from row to row, notice that when I created my statement, I set the type as TYPE_SCROLL_INSENSITIVE. So I should get back a scrollable result set, regardless of whether I'm working with HSQLDB or MySQL. I'll place the cursor after the call to the displayData method, and first I'll move the cursor to the last row of the ResultSet, I'll call rs.Last, then I'll do some System.output, and I'll output (Number of rows), and I'll append to that the current row number using the ResultSet getRow method.

I'll save and run that code, and at the end of the display, I see that the number of rows is 50, and that's correct. Now I'll add some code to move back to the first row, rs.First, and then once again I'll use some System.output, and I'll output the string, The first state is, and I'll append to that the value of the state name column using rs.getString, and I'll pass in the name of the column stateName. I'll save and run that code, and I see that the first state is Alaska, this table has the states in alphabetical order, now we'll add some code to move the cursor to the last row, rs.Last, and I'll make a copy of this output, and I'll paste it here, and I'll change from the first state to the last state, and I'll run that code, and I see that the last state alphabetically is Wyoming.

Finally, I'll move the cursor to a specific row using rs.absolute, and I'll pass the value of 10, and once again I'll pasted my output code, and I'll change from first to 10th, and I'll run that code. And I'll see that I can successfully move the cursor as much as I need to. In this code, I'm scrolling first forward through all the data, then I'm moving to the end to get the number of rows, back to the beginning, back to the end again, and then to a specific row by its integer value. So that's a look at how you can use scrollable result sets.

Now let's take a look at what happens if you don't specify that you want a scrollable ResultSet. I'm going to make a copy of this line of code that creates the Statement, and I am going to comment those new lines out, those are my backup, because I'm going to make some changes to the original code. Now I'll go to my CreateStatement method call, and I'll get rid of the options that I was passing in. Now, notice I'm working with HSQLDB, and I'll run the code, and this time I'm able to look forward through the data, but then I get an exception SQLFeaturedNonSupportedException, and that's because with HSQLDB the ResultSet by default isn't scrollable.

It's a forward-only ResultSet. Now I'll change my databaseType from HSQLDB to MySQL, and I'll run the code again, and this time it works, and that's because with MySQL, you get a scrollable ResultSet automatically. To fix this and make sure that this code will work fine with either database, I'll always explicitly say that I want a scrollable ResultSet. So I'll go back to the code again, I'll delete these two lines, and I'll uncomment these, I'll save and run the code, and I see that it works fine with MySQL, and I'll switch back to HSQLDB, and I'll save and run again, and I'll see it works there as well.

So for maximum portability, be explicit about the type of the ResultSet that you want, and you set those options when you create the Statement object.

Show transcript

This video is part of

Image for Java Database Integration with JDBC
Java Database Integration with JDBC

32 video lessons · 7093 viewers

David Gassner
Author

 
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

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

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.


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.

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 preferences from the dropdown menu.

Continue to classic layout Stay on new layout
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.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

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
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.