Java Reference
In-Depth Information
For example, if the column you are interested in viewing contains an int,
you need to use one of the getInt() methods of ResultSet:
public int getInt(String columnName) throws SQLException.
Returns
the int in the current row in the column named columnName.
public int getInt(int columnIndex) throws SQLException. Returns the
int in the current row in the specified column index. The column index
starts at 1, meaning the first column of a row is 1, the second column of a
row is 2, and so on.
Using the column index is more efficient in terms of performance as
opposed to using the column name. The get methods that use the column
name have to determine which index to use. They then actually invoke the
get method that takes in an index. Knowing the column index saves you at
least two method calls behind the scenes. That being said, I like to use the
column name whenever feasible because it makes the code easier to use,
and I do not have to worry about the order of the columns in the result set.
As you may expect, there are get methods in the ResultSet interface for each
of the eight Java primitive types, as well as common types such as
java.lang.String, java.lang.Object, and java.net.URL. There are also methods
for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp,
java.sql.Clob (Character Large Object), and java.sql.Blob (Binary Large
Object). (Check the documentation for more information about using these
SQL data types.)
I added the following showAllMovies() method to the MovieDatabase class
from earlier to demonstrate how a ResultSet object is navigated from start to
finish, and also to demonstrate how to access the data in each row of a Result-
Set. Study the method carefully and try to determine what it does.
public void showAllMovies()
{
try
{
Statement selectAll = connection.createStatement();
String sql = “SELECT * FROM Movies”;
ResultSet results = selectAll.executeQuery(sql);
while(results.next())
{
int number = results.getInt(1);
String title = results.getString(“title”);
String category = results.getString(3);
String format = results.getString(4);
Movie movie = new Movie(number, title,
category, format);
Search WWH ::




Custom Search