<%@page contentType="text/html;charset=GBK"%>
<HTML>
<HEAD>
<TITLE>用JDOM实现数据库到XML的转换</TITLE>
</HEAD>
<BODY>
<%@page import="org.jdom.*"%>
<%@page import="java.*"%>
<%
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://10.40.14.54:1433;DatabaseName=DB_CUSTOM";
//载入jdbc odbc的驱动程序
String user="lgz";
String password="lgz";
Connection conn= DriverManager.getConnection(url,user,password); //连接数据库
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
//创建一个statement
String sql="select * from client"; //定义查询的SQL语句
ResultSet rs=stmt.executeQuery(sql); //执行查询
Document document=new Document(new Element("联系人列表"));//创建文档
ResultSetMetaData rsmd = rs.getMetaData(); //获取字段名
int numberOfColumns = rsmd.getColumnCount(); //获取字段数
int i=0;
while(rs.next()){ //将查询结果取出
Element element0=new Element("联系人"); //创建元素 生成JDOM树
document.getRootElement().addContent(element0);
for (i=1; i<=numberOfColumns;i++)
{ String date=new String(rs.getString(i).getBytes("ISO-8859-1"),"gb2312"); //代码转换
Element element=new Element(rsmd.getColumnName(i)).setText(date);
element0.addContent(element);
}
}
rs.close(); //关闭结果集
stmt.close(); //关闭statement
conn.close(); //关闭连接
XMLOutputter outp = new XMLOutputter();
outp.output(document, new FileOutputStream("d:\\data.xml")); //输出XML文档
out.print("XML 文档生成完毕!");
%>
<a href="file:///d|/data.xml">点击打开产生的XML文档 </a>
</BODY>
</HTML>
|