I want to run SQL query in Java and the result of the query is in xml. The query result is as follows -
<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>
Now I want to export the above xml into an external file called QueryResult.xml using java. I have tried using the below java script but unable to save the file.
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);
}
Query Name:
select Distinct Unique_id, DoorNo, StreetNo, Siteno from Table Name where
Unqiue_id IN ( '6124','6125') FOR XML RAW ('Rows'), ROOT ('Root'), ELEMENTS XSINIL;