import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class XmlNameWriter {
/**
* 利用dom4j生成XML
*
* @author Daniel Cheng
*/
static Logger logger=Logger.getLogger(XmlNameWriter.class.getClass());
public void createXML() {
PropertyConfigurator.configure ( "D:\\workspace\\testlog4j.properties" ) ;
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/zczh?characterEncoding=gbk";
String username="root";
String password="233111";
Connection conn=null;
Document doc = DocumentHelper.createDocument();
Element rootEle = doc.addElement("tables");
try{
Class.forName(driver);
conn=DriverManager.getConnection(url, username, password);
ResultSet rs=null;
DatabaseMetaData dbmd=conn.getMetaData();
rs=dbmd.getTables(null, null, null, null);
while(rs.next()){
[b]Element nameEle = rootEle .addElement("table");
String tablename=rs.getString(3);
nameEle.setText(tablename);
logger.debug(tablename+"表名已读取到");[/b]//此处获取的中文表名乱码,我在论坛里找了几个设置字符集的方法,试了之后依然乱码。怎样解决?
}
if(rs!=null){
rs.close();
}
}catch(SQLException e){
logger.error(e.getMessage());
}catch(ClassNotFoundException e){
logger.error("error:"+e.getMessage());
}finally{
if(conn!=null){
try{
conn.close();
}catch(SQLException e){
logger.error("error:"+e.getMessage());
}
}
}
try {
Writer out = new FileWriter("tables.xml");
//格式化输出,类型IE浏览一样
OutputFormat format = OutputFormat.createPrettyPrint();
//OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("gbk");
//创建写出对象
XMLWriter writer = new XMLWriter(out, format);
writer.write(doc);
writer.close();
System.out.println("生成tables.xml成功。");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("失败了。");
}
}
public static void main(String[] args) {
new XmlNameWriter().createXML();
}
}