Database Reference
In-Depth Information
++
count
;
}
rs
.
close
();
// close result set
s
.
close
();
// close statement
System
.
out
.
println
(
"Number of rows returned: "
+
count
);
The
ResultSet
object returned by the
getResultSet()
method of your
Statement
object has its own methods, such as
next()
to fetch rows and various
get
XXX
()
methods
that access columns of the current row. Initially, the result set is positioned just before
the first row of the set. Call
next()
to fetch each row in succession until it returns false.
To determine the number of rows in a result set, count them yourself, as shown in the
preceding example.
To access column values, use methods such as
getInt()
,
getString()
,
getFloat()
,
and
getDate()
. To obtain the column value as a generic object, use
getObject()
. The
argument to a
get
XXX
()
call can indicate either column position (beginning at 1, not 0)
or column name. The previous example shows how to retrieve the
id
,
name
, and
cats
columns by position. To access columns by name instead, write the row-fetching loop
as follows:
while
(
rs
.
next
())
// loop through rows of result set
{
int
id
=
rs
.
getInt
(
"id"
);
String
name
=
rs
.
getString
(
"name"
);
int
cats
=
rs
.
getInt
(
"cats"
);
System
.
out
.
println
(
"id: "
+
id
+
", name: "
+
name
+
", cats: "
+
cats
);
++
count
;
}
To retrieve a given column value, use any
get
XXX
()
call that makes sense for the data
type. For example,
getString()
retrieves any column value as a string:
String
id
=
rs
.
getString
(
"id"
);
String
name
=
rs
.
getString
(
"name"
);
String
cats
=
rs
.
getString
(
"cats"
);
System
.
out
.
println
(
"id: "
+
id
+
", name: "
+
name
+
", cats: "
+
cats
);
Or use
getObject()
to retrieve values as generic objects and convert the values as nec‐
essary. The following example uses
toString()
to convert object values to printable
form:
Object
id
=
rs
.
getObject
(
"id"
);
Object
name
=
rs
.
getObject
(
"name"
);
Object
cats
=
rs
.
getObject
(
"cats"
);
System
.
out
.
println
(
"id: "
+
id
.
toString
()
+
", name: "
+
name
.
toString
()
+
", cats: "
+
cats
.
toString
());