0

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;

1 Answer 1

1
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.

Regarding your code, 1. you forgot to make next() on result set; 2. you don't need SQLXML here at all.

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.