/*
Output:
xsi:schemaLocation="http://java.sun.com/xml/ns/jdbc http://java.sun.com/xml/ns/jdbc/webrowset.xsd">
SELECT * FROM survey WHERE id='1'
1008
true
1000
0
2
0
0
0
true
ResultSet.TYPE_SCROLL_INSENSITIVE
false
survey
com.sun.rowset.providers.RIOptimisticProvider
Sun Microsystems Inc.
1.0
2
1
2
1
false
false
false
1
true
true
11
ID
ID
PUBLIC
10
0
SURVEY
4
INTEGER
2
false
false
false
1
false
true
32766
NAME
NAME
PUBLIC
2147483647
0
SURVEY
12
VARCHAR
1
nameValue
*/
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.rowset.WebRowSet;
import com.sun.rowset.WebRowSetImpl;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getHSQLConnection();
System.out.println("Got Connection.");
Statement st = conn.createStatement();
st.executeUpdate("create table survey (id int,name varchar);");
st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
st.executeUpdate("insert into survey (id,name ) values (2,'anotherValue')");
WebRowSet webRS;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
webRS = null;
String sqlQuery = "SELECT * FROM survey WHERE id='1'";
webRS = new WebRowSetImpl();
webRS.setCommand(sqlQuery);
webRS.execute(conn);
FileWriter fw = null;
File file = new File("1.xml");
fw = new FileWriter(file);
System.out.println("Writing db data to file " + file.getAbsolutePath());
webRS.writeXml(fw);
// convert xml to a String object
StringWriter sw = new StringWriter();
webRS.writeXml(sw);
System.out.println("==============");
System.out.println(sw.toString());
System.out.println("==============");
fw.flush();
fw.close();
rs.close();
stmt.close();
conn.close();
}
private static Connection getHSQLConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
public static Connection getMySqlConnection() throws Exception {
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/demo2s";
String username = "oost";
String password = "oost";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static Connection getOracleConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:databaseName";
String username = "userName";
String password = "password";
Class.forName(driver); // load Oracle driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
SaveWebRowSetToXMLFile.zip( 3,849 k)