简体   繁体   English

数据库中的行作为字符串(JDBC)

[英]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? 是否有直接方法可以将ResultSet中的所有元素作为字符串获取? JDBC JDBC

You may use BasicRowProcessor from Apache commons, Dbutils 您可以使用BasicRowProcessorApache的公地,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: 如果要摆脱columNames:

String s = m.values().toString();

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. 不,这是不可能的-无论如何,您至少需要调用一次getString() The best you can do is to concatenate your fields in SQL, eg 最好的办法是在SQL中连接字段,例如

SELECT col1 || ', ' || col2 || ', ' || col3 ... FROM my_table

and call resultSet.next().getString(1) to get that. 并调用resultSet.next().getString(1)来获取。

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. 更新 (基于评论)我认为(实际上取决于您的JDBC驱动程序和数据库,您必须进行测量才能确定)在发送数据(从数据库到您的数据库)之间的数据量差异不大应用))按列还是一个连接字符串。 In fact, the latter may even be more expensive if you have numbers / dates because they'll likely occupy more bytes formatted as text. 事实上,后者甚至更加昂贵,如果你有一个数字/日期,因为他们很可能会占据文本格式多个字节。

There's not a single method call to do it, but you can use something like this to build a String: 没有一个方法可以调用它,但是您可以使用类似的方法来构建一个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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM