我尝试使用此 java 代码使用 sql 查询从数据库中导出数据,但得到一个空指针异常。不知道删除它。我在粗体字的行中遇到了这个异常。
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager
.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "hr", "hr");
ResultSet rs = con.createStatement().executeQuery("select * from departments");
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int i = 1; i <= colCount; i++) {
String columnName = rsmd.getColumnName(i);
Object value = rs.getObject(i);
Element node = doc.createElement(columnName);
row.appendChild(node);
**node.appendChild(doc.createTextNode(value.toString()));**
}
}
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
System.out.println(sw.toString());
con.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
堆栈跟踪 :
java.lang.NullPointerException
at org.ProjectXML.ui.DataBaseToXML.main(DataBaseToXML.java:61)
有任何想法吗?