我想在Java中运行SQL查询,查询结果在xml中。查询结果如下-
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Rows>
<Unique_id>6124</Unique_id>
<DoorNo>12</DoorNo>
<StreetNo>1</StreetNo>
<SiteNo>84904</SiteNo>
</Rows>
<Rows>
<Unique_id>6125</Unique_id>
<DoorNo>12</DoorNo>
<StreetNo>2</StreetNo>
<SiteNo>84904</SiteNo>
</Rows>
</Root>
现在我想使用 java 将上述 xml 导出到名为 QueryResult.xml 的外部文件中。 我尝试使用下面的java脚本但无法保存文件。
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection("jdbc:sqlserver://sqldatabase:1009;
databaseName=DatabaseName;user=UserName;password=1234");
PreparedStatement ps=con.prepareStatement(QueryName);
ResultSet rs=ps.executeQuery();
SQLXML xmlVal1= rs.getSQLXML(1);
String val = xmlVal1.getString();
try (PrintWriter out = new PrintWriter(new File("Output.xml"))) {
out.println(val);
}
查询名称:
select Distinct Unique_id, DoorNo, StreetNo, Siteno from Table Name where
Unqiue_id IN ( '6124','6125') FOR XML RAW ('Rows'), ROOT ('Root'), ELEMENTS XSINIL;
请您参考如下方法:
SQLXML xmlVal= rs.getSQLXML(1);
String val = xmlVal.getString();
try (PrintWriter out = new PrintWriter("out.xml")) {
out.println(val);
}
Here is the Oracle Tutorial with code examples .
关于你的代码, 1. 你忘记对结果集执行 next() ; 2. 这里根本不需要 SQLXML。
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection("jdbc:sqlserver://sqldatabase:1009;
databaseName=DatabaseName;user=UserName;password=1234");
PreparedStatement ps=con.prepareStatement(QueryName);
ResultSet rs=ps.executeQuery();
rs.next();
String val = rs.getString(1);
try (PrintWriter out = new PrintWriter(new File("Output.xml"))) {
out.println(val);
}