使用Java将SQL查询结果输出为平面文件 [英] Output SQL query results to flat-file with Java

查看:279
本文介绍了使用Java将SQL查询结果输出为平面文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中有一种简单或直接的方式将DB查询的结果输出到文件(csv,tab等)。也许在Hibernate中?

Is there an easy or straightforward way in Java to output the results of a DB Query to a file (either csv, tab, etc). Perhaps even in Hibernate?

我知道一个查询结果可以转储到DB服务器上的一个平面文件。我正在寻找一种方法,一个应用程序可以运行查询,并获得这些结果到一个文件。

I know that a query results can be dumped to a flat file on the DB Server. I am looking for a way that an application can run a query and get those results into a file.

我实现一个选项是只是迭代结果集和输出记录一次一行用分隔符分隔。但是如果有一个内置的方式,或者一个Hibernate的方式 - 会更好!

I realize one option is to just iterate over the result set and output the records one row at a time separating with a delimiter. But if there is a built in way, or a Hibernate way - that would be much better!

我真正寻找的是一个方法来做这个代码像 - 当应用程序正在运行时)。这样服务器可以接受查询,对数据库运行它,将输出发送到一个平面文件。

What I am really looking for was a way to do this in code (like - when an application is running). That way a server could take a query, run it against the database, send the output to a flat-file.

发送查询的服务器不需要文件本身,只是知道它工作。因此,如果存在可将输出重定向到Oracle数据库服务器可访问的目录中的平面文件的SQL(对于Oracle DB),这也可以工作。我真的不必实际写入文件在Java服务器 - 只是触发文件创建基于查询它有。

The server sending the query doesn't really need the file itself, just to know it worked. So if there is SQL (for an Oracle DB) that could redirect the output to a flat-file in a directory that the Oracle DB Server has access to - that would work too. I don't really have to actually write the file in the Java Server - just trigger the file creation based on the query it has.

希望这是有意义的。 p>

Hopefully that makes sense.

推荐答案

您可以将会话的EntityMode更改为DOM4J,以便Hibernate将返回表示为XML文档的数据,而不是POJO图。

You can change the EntityMode of your Session to "DOM4J" so that Hibernate will return the data represented as an XML document instead of a POJO graph.

xmlSession = session.getSession(EntityMode.DOM4J);
Element elem = (Element) xmlSession.load(SomePersistentClass.class, id);
System.out.println(elem.asXML());

然后,您可以轻松地将其写入文件系统或进行后续转换。

You could then easily write this to the file system or do subsequent transformations.

这篇关于使用Java将SQL查询结果输出为平面文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆