Java SAX解析器解析XML配置文件,连接数据库

来源:互联网 发布:mysql 触发器 本表 编辑:程序博客网 时间:2024/04/28 17:41

/*
 * 从XML文件中读取配置信息,并通过配置信息返回数据库连接
 *
 */
package com.augow.xmlconfigreader;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import java.util.Properties;

/*
 * SAX方式用于解析XML文件的解析器
 */

public class ConfigParser extends DefaultHandler
{
    /*props:用于存放解析器解析出来的的节点和节点对应的属性,为哈希表
     * currentName:当前节点的名称
     * currentValue:用于存放当前节点所对应的属性值
     */
    private Properties props;
    private String currentName;
    private StringBuffer currentValue = new StringBuffer();

   
 public ConfigParser()
    {
        this.props=new Properties();
    }
 
 
    public Properties getPrpos()
    {
        return this.props;
    }
   
   
    public String getCurrentName()
    {
        return currentName;
    }
   
   
    /*
     * 读取<xxx>中的值xxx并将其付给qname,通知解析器解析当前节点对应的值。同时对currentValue缓冲器清空,用来保存当前qname对应属性值。
     * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
   public void startElement(String uri,String localName,String qName,Attributes attributes)
    throws SAXException
    {
        currentValue.delete(0,currentValue.length());
        this.currentName=qName;
    }
   
   
      /*读取<xxx></xxx>之间的属性值,并将其首先以字符形式保存至字符数组ch中,并记录对应长度,以确保以
       * length为长度的字符为一个整体,然后讲字符数组中的内容按照length长度为整体加到currentValue缓冲器中
       * 每次读取xml文件后只会在ch中保存当前所解析到的值,currentValue中也只会有当前的节点所对应的唯一值
     */
    public void characters(char[] ch,int start,int length)
    throws SAXException
    {
        currentValue.append(ch,start,length);
    }
   
   
     /* 当遇到</xxx>时,将当前的qname,和qname所对应的位于currentValue缓冲器中的值保存到props这个哈希表中去,供外部程序调用
     * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
     */
    public void endElement(String uri, String localName, String qName)
    throws SAXException
    {
        props.put(qName.toLowerCase(), currentValue.toString().trim());
    }

 

}

 /*
 * 从XML文件中读取配置信息,并通过配置信息返回数据库连接
 *
 */

package com.augow.xmlconfigreader;

import java.util.Properties;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/*
 * 用于实例化解析器,并利用解析器对XML文件进行解析并将解析结果返回,通过提供的获取结果的
 * 方法供外部程序调用
 */
public class XmlReader
{
    //用于存放解析结果的哈希表
    private Properties props;
   
    public XmlReader(String filename)
    {
        try
            {
                parse(filename);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
       
    public Properties getProps()
    {
        return this.props;
    }
   
   
    /*
     * 用于分析xml文件的方法
     */
    public  void parse(String filename)
    throws Exception
    {
        //实例化解析器
        ConfigParser handler = new ConfigParser();
       
        //实例化用于分析的工厂
        SAXParserFactory factory = SAXParserFactory.newInstance();
       
        //实例化分析类
        SAXParser parser = factory.newSAXParser();
       
        //得到xml文件对应的路径
        URL confURL = XmlReader.class.getClassLoader().getResource(filename);
        try
        {
            parser.parse(confURL.toString(), handler);
            props = handler.getPrpos();
        }
        finally
        {
            /*
             *销毁已过期对象
             */
            factory=null;
            parser=null;
            handler=null;
        }

    }
   
   
    /*
     * 提供给外部程序调用的用于返回程序所对应需要的xml文件属性的方法
     */
    public String getElementValue(String elementName)
    {
        //elementValue:对应于elementName的节点的属性值
        String elementValue=null;
        elementValue=props.getProperty(elementName);
        return elementValue;
    }
}

 

/*
 * 从XML文件中读取配置信息,并通过配置信息返回数据库连接
 *
 */
package com.augow.xmlconfigreader;

import java.sql.*;

/*
 * 用于创建并返回由指定Xml配置文件所配置的数据库连接
 */
public  class DBConnection
{
    private  static Connection conn=null;
    public DBConnection(){}
    /*
     * 创建指定的数据库连接
     */
    public static Connection CreateConnection()
    {
        XmlReader p=new XmlReader("XMLConfigure.xml");
        try
        {   
            /*
             * 加入jdbc驱动包
             */
            Class.forName(p.getElementValue("dbtype")).newInstance();
            System.out.println("Success loading "+p.getElementValue("dbtype"));
        }catch(Exception e)
        {
            System.out.println("Error loading "+p.getElementValue("dbtype"));
        }
        try
        {
            conn=DriverManager.getConnection("jdbc:mysql://"+
                    p.getElementValue("dbhost")+"/"+p.getElementValue("dbname")+
                    "?user="+p.getElementValue("dbuser")+"&password="+
                    p.getElementValue("dbpassword")+"&characterEncoding=gb2312");
            System.out.println("Success connect Database!");
            System.out.println("Success return a connection to the database!");
            return conn;
        }catch(SQLException e)
        {
          System.out.println(e.getMessage());
          return null;
        }
       
    }

}

/*
 * 从XML文件中读取配置信息,并通过配置信息返回数据库连接
 *
 */
package com.augow.xmlconfigreader;
import java.sql.*;

/*
 * 用于测试
 */
public class Test
{

    private static Statement stat=null;
    public static void main(String[] args)
    {

        Connection con=DBConnection.CreateConnection();
        try
        {
            ResultSet rs = null;
            stat= con.createStatement();
            rs=stat.executeQuery("select sname from student where snum='0202'");
            while(rs.next())
            {
              System.out.println(rs.getString("sname"));

            }
          con.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
              
    }

}

0 0
原创粉丝点击