Is there a direct method to get the all the elements in a row from the ResultSet as String? JDBC
-
How would you want the data to be represented?skaffman– skaffman2009-10-27 22:20:23 +00:00Commented Oct 27, 2009 at 22:20
-
String data = "value1, value2, value3" but not using getString("") or similar methods and concatenating them!Vishal– Vishal2009-10-27 22:21:53 +00:00Commented Oct 27, 2009 at 22:21
-
2Why don't you want to concatenate or use StringBuffer to create your own String?Thomas Owens– Thomas Owens2009-10-27 22:27:01 +00:00Commented Oct 27, 2009 at 22:27
-
Thanks, looking for another solution.Vishal– Vishal2009-10-27 22:34:54 +00:00Commented Oct 27, 2009 at 22:34
-
1BTW if you are having performance problems, bear in mind that in most situations, the problem is not in the information processing, but the time spent on the network. So, instead of trying to tweak your row processing, you should better figure out how to send less info at a time. If you don't believe me, see how much does a java program takes to process 2 mb or data vs. sending 2 mb of data through the net.OscarRyz– OscarRyz2009-10-27 22:47:09 +00:00Commented Oct 27, 2009 at 22:47
3 Answers
You may use BasicRowProcessor from Apache commons, Dbutils
ResultSet rs = ....
RowProcessor rp = new BasicRowProcessor();
Map m = rp.toMap( rs );
String s = m.toString();
And you'll have then as:
{ id = 1, name = Oscar, lastName = Reyes }
etc.
If you want to get rid of the columNames:
String s = m.values().toString();
1 Comment
BasicRowProcessor.toMap() (and subsequent code to access that map) an absolute performance killer on large datasets. toArray() is better, raw ResultSet access is better yet.There's not a single method call to do it, but you can use something like this to build a String:
StringBuilder sb = new StringBuilder();
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
for (int i = 1; i <= numberOfColumns; i++) {
sb.append(rs.getString(i));
if (i < numberOfColumns) {
sb.append(", ");
}
}
String data = sb.toString();
1 Comment
I've got to ask - why would you need something like that?
And no, it's not possible - you would need to call getString() at least once no matter what. The best you can do is to concatenate your fields in SQL, e.g.
SELECT col1 || ', ' || col2 || ', ' || col3 ... FROM my_table
and call resultSet.next().getString(1) to get that.
Update (based on comment) I don't think (that depends on your JDBC driver and database, really - you'll have to measure to find out) that there is a big difference in data volume between sending data (from DB to your app) by columns vs one concatenated string. In fact, the latter may even be more expensive if you have numbers / dates because they'll likely occupy more bytes formatted as text.