How to check if resultset has one row or more with JDBC?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- How to maintain order of key-value in DataFrame sa
You don't need JDBC for this. The normal idiom is to collect all results in a collection and make use of the collection methods, such as
List#size()
.where the
list()
method look like something:My no-brainer suggestion: Fetch the first result row, and then try to fetch the next. If the attempt is successful, you have more than one row.
If there is more than one row and you want to process that data, you'll need to either cache the stuff from the first row, or use a scrollable result set so you can seek back to the top before going through the results.
You can also ask SQL directly for this information by doing a
SELECT COUNT(*)
on the rest of your query; the result will be 0, 1 or more depending on how many rows the rest of the query would return. That's pretty easy to implement but involves two queries to the DB, assuming you're going to want to read and process the actual query next.Get the Row Count using
ResultSetMetaData
class.From your code u can create
ResultSetMetaData
like :You didn't ask this one, but you may need it:
Normally, we don't need the row count because we use a WHILE loop to iterate through the result set instead of a FOR loop:
However, in some cases, you might want to window the results, and you need the record count ahead of time to display to the user something like
Row 1 to 10 of 100
. You can do a separate query withSELECT COUNT(*)
first, to get the record count, but note that the count is only approximate, since rows can be added or removed between the time it takes to execute the two queries.Sample from ResultSet Overview
If you want to make sure that there is exactly one row, you can ensure that the first row is the last:
There are many options, and since you don't provide more context the only thing left is to guess. My answers are sorted by complexity and performance ascending order.
select count(1) FROM ...
and get the answer. You'd have to run another query that actually selects and returns the data.rs.next()
and count until you're happy. Then if you still need the actual data re-run same query.rs.next()
couple of times and then rewind back withrs.previous()
.