Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet234/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   230   231   232   233   234   235   236   237   ...   245
Bog'liq
Java 17 Recipes

 How It Works
Ordinary ResultSet objects allow results to be fetched in a forward direction. An 
application can process a default ResultSet object from the first record retrieved 
forward to the last. Sometimes an application requires more functionality when it comes 
to traversing a ResultSet object. For instance, let’s say you want to write an application 
Chapter 12 Working With Databases


463
that allows someone to display the first or last record retrieved, or perhaps page 
forward or backward through results. You could not do this very easily using a standard 
ResultSet. However, by creating a scrollable ResultSet, you can easily move backward 
and forward through the results.
To create a scrollable ResultSet object, you must first create an instance of 
Statement or PreparedStatement that can create a scrollable ResultSet. When 
creating the Statement, you must pass the ResultSet scroll type constant value to the 
Connection object’s createStatement() method. Likewise, you must pass the scroll 
type constant value to the Connection object’s prepareStatement() method when using 
PreparedStatement.
You must also pass a ResultSet concurrency constant to advise whether ResultSet 
is intended to be updatable. The default is ResultSet.CONCUR_READ_ONLY, which means 
that the ResultSet object is not updatable. The other concurrency type is ResultSet 
.CONCUR_UPDATABLE, which signifies an updatable ResultSet object.
In the solution to this recipe, a PreparedStatement object is used. Creating a 
PreparedStatement object that can generate a scrollable ResultSet looks like the 
following line.
pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Once the PreparedStatement object has been created, a scrollable ResultSet is 
returned. You can traverse in several directions using a scrollable ResultSet by calling 
the ResultSet methods indicating the direction you want to move or the placement that 
you want to be. The following line of code retrieves the first record within the ResultSet.
ResultSet rs = pstmt.executeQuery();
rs.first();
The solution to this recipe demonstrates a few different scroll directions. Specifically
you can see that the ResultSet first(), next(), last(), and previous() methods 
are called to move to different positions within the ResultSet.
Scrollable ResultSet objects have a niche in application development. They are one 
of those niceties that are there when you need them, but they are also something that 
you might not need very often.
Chapter 12 Working With Databases


464

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   230   231   232   233   234   235   236   237   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling