我正在开发一个项目,我需要从数据库中获取数据并以xml格式存储它。我使用以下代码从数据库中提取数据。代码如下
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String args[]) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=null;
con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe", "system","1234");
ResultSet rs = con.createStatement().executeQuery("select *from people");
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);
if (value != null)
node.appendChild(doc.createTextNode(value.toString()));
else
node.appendChild(doc.createTextNode(""));
row.appendChild(node);
row.appendChild(node);
row.appendChild(node);
}
}
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();
}
}
我将整个数据存储在表人中,但是我需要根据sql查询中的条件来提取特定人的数据,例如“select * from first where first =?”。我尝试了很多方法来获取特定人员的数据,但我无法获取数据。请建议我如何从数据库中获取特定人员的数据。以及我需要对代码进行哪些更改以获取特定人员的数据。
答案 0 :(得分:0)
如何将名称作为参数:
String searchedName = args[0];
ResultSet rs = con.createStatement().executeQuery("select * from people where firstname = '"+searchedName+"'");
答案 1 :(得分:0)
由于您的代码在main方法中,您可以通过命令行传递值:java Main Parameter_personName。 否则,您可以从文本文件中读取它并将其作为参数传递给您的查询。