Vishal
Vishal

Reputation: 20617

Row from a database as string (JDBC)

Is there a direct method to get the all the elements in a row from the ResultSet as String? JDBC

Upvotes: 2

Views: 6497

Answers (3)

ChssPly76
ChssPly76

Reputation: 100706

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.

Upvotes: 3

OscarRyz
OscarRyz

Reputation: 199225

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();

Upvotes: 6

Jason Day
Jason Day

Reputation: 8839

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();

Upvotes: 3

Related Questions