java连接oracle数据库的时候, 需要从特定地方读取xml文件中的sql去get结果集,

xml文件放在和java文件: SqlLoaderFromXML的目录下OracleSQL, xml文件名:Product.xml,

<?xml version="1.0" encoding="GB2312"?>
<SQLSTRING>

<Products>
select distinct productid
from table_product_list
</Products>

</SQLSTRING>

java sample如下:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class SqlLoaderFromXML {

private static String sqlPath = "./OracleSQL/";
private static String sqlFile = sqlPath + "Product.xml";

public static String loadSqlFromXml(String xmlFile, String xpath) throws FileNotFoundException, DocumentException {

InputStream input = new FileInputStream(xmlFile);
SAXReader saxReader = new SAXReader(false);
Document sqlDoc = saxReader.read(input);
Node node = sqlDoc.selectSingleNode(xpath);
return node.getText();

}

public static void main(String[] args) throws Exception {

String sqlString = loadSqlFromXml(sqlFile, "//SQLSTRING/Products");

System.out.println("SQL From XML File: \n" + sqlString);
}
}

可以打包后续代码共享

05-11 22:35