以文本方式查看主题

-  W3CHINA.ORG讨论区 - 语义网·描述逻辑·本体·RDF·OWL  (http://bbs.xml.org.cn/index.asp)
--  『 XML 与 数据库 』  (http://bbs.xml.org.cn/list.asp?boardid=17)
----  XML与数据库的转换——程序已有,还有点问题,高手指点下!!!  (http://bbs.xml.org.cn/dispbbs.asp?boardid=17&rootid=&id=19152)


--  作者:wawehi
--  发布时间:6/2/2005 3:36:00 PM

--  XML与数据库的转换——程序已有,还有点问题,高手指点下!!!
功能很简单,得用java语言,从access数据库中,把一些数据导入到SQL数据库中。
                                   作者:sirix   Email:nevinguo@163.com
  需求:

  原Access数据库表结构:

  表:production

    产品型号   字符串型………产品编号

    零件图号   字符串型……….零件编号

    图号       字符串型……….工具编号

  SQL数据表结构:

  Project     产品表

    Id         int           标识

    Number…  varchar64     编号

    Product    零件表

    Id         int           标识

    pid         int           产品标识号(与project表中的id相关联)

    Number…  varchar64     编号

  Componenttype   与零件对应的生产工具表

      Id         int           标识

      aid         int           零件标识(与product表中的id关联)

      Number…  varchar64     编号

  要求把原来的编号分别放到下面的SQL三个表格中,并用id关联起来。

  考虑到数据库连接可能有变化,决定使用xml来配置数据连接。Dbs.xml文件内容如下:


<?xml version="1.0" encoding="GBK"?>

<dbcopy>   

  <source>

     <class>sun.jdbc.odbc.JdbcOdbcDriver</class>

    <url>jdbc:odbc:asrs</url>

    <user>""</user>

    <password>""</password>

  </source>

  <dest>

    <class>com.microsoft.jdbc.sqlserver.SQLServerDriver</class>

    <url>jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=vxms</url>

    <user>vxms</user>

    <password>vxms</password>

  </dest>

</dbcopy>

文件ConnPara.java,表示以类形式表示的数据库连接参数。

public class ConnPara

{

    String dbClass=null;

    String url=null;

    String username=null;

    String password=null;  

    public ConnPara()  {   }

    public ConnPara(String pdbClass,String purl,String pusername,String ppassword)

    {

        dbClass=pdbClass;

        url=purl;

        username=pusername;

        password=ppassword;     

    }

    public String getDbClass(){return dbClass;}

    public String getUrl(){return url;}

    public String getUsername(){return username;}

    public String getPassword(){return password;}

    public void setDbClass(String str){ dbClass=str;}

    public void setUrl(String str){ url=str;}

    public void setUsername(String str){username=str;}

    public void setPassword(String str){password=str;}

}


文件DbXmlParser.java封装了对xml文件的操作。

import javax.xml.parsers.*;

import org.w3c.dom.*;

import org.xml.sax.*;

import java.io.*;

public class DbXmlParser

{

    static  String  xmlfile;

    public DbXmlParser(String filename)

    {

        xmlfile=filename;

    }

    public static Element loadDocument()

    {

        try

        {

            //工厂

            DocumentBuilderFactory dcfactory=DocumentBuilderFactory.newInstance();

            //文档构造器

            DocumentBuilder db=dcfactory.newDocumentBuilder();

            //构造的文档

            Document doc=db.parse(xmlfile);

            //根元素

            Element root=doc.getDocumentElement();

             return root;

            }catch( ParserConfigurationException e){

            System.out.println("ParserConfigurationException");

            e.printStackTrace();

        }catch(IOException e)      {

            System.out.println("IOException ");

            e.printStackTrace();

        }catch(SAXException e)     {

            System.out.println("SAXException ");

            e.printStackTrace();

        }catch(Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    public ConnPara getSource()

    {

        Element root=loadDocument();

        if( root==null) {  return null;   }

        NodeList nodes=root.getElementsByTagName("source");

        if(nodes.getLength()>0)

        {       

            Node node=nodes.item(0);

            String connclass=getChildElementValue(node,"class");

            String url=getChildElementValue(node,"url");

            String username=getChildElementValue(node,"user");

            String password=getChildElementValue(node,"password");

            return new ConnPara(connclass,url,username,password);

        }

        return null;       

    }   

    public  ConnPara getDest()

    {

        Element root=loadDocument();

        if( root==null) return null;

        NodeList nodes=root.getElementsByTagName("dest");

        if(nodes.getLength()>0)

        {       

            Node node=nodes.item(0);

            String connclass=getChildElementValue(node,"class");

            String url=getChildElementValue(node,"url");

            String username=getChildElementValue(node,"user");

            String password=getChildElementValue(node,"password");

            return new ConnPara(connclass,url,username,password);

        }

        return null;       

    }

    //得到子元素的值

    private  String getChildElementValue(Node node,String subTagName)

     {

            String returnString = "";

            if(node != null)

            {

                NodeList children = node.getChildNodes();

                for(int innerLoop = 0; innerLoop < children.getLength(); innerLoop++)

                {

                    Node child = children.item(innerLoop);

                    if(child == null || child.getNodeName() == null || !child.getNodeName().equals(subTagName))

                        continue;

                    Node grandChild = child.getFirstChild();  

                    if(grandChild.getNodeValue() != null)

                        return grandChild.getNodeValue();

                }

            }

            return returnString;       

    }   
}


文件DbInput.java则是真正的数据拷贝部分:

import java.sql.*;

public class DbInput

{

    Connection src=null;

    Connection dest=null;

    Connection connformax=null;

    ConnPara srcPara;

    ConnPara destPara;

    public DbInput(){}

    public void dbInit()

    {

        DbXmlParser xmlparser=new DbXmlParser("dbs.xml");

        srcPara=xmlparser.getSource();

        destPara=xmlparser.getDest();

        try {

           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver" );

           Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

           src = DriverManager.getConnection( srcPara.getUrl(), srcPara.getUsername(),srcPara.getPassword());

           dest =DriverManager.getConnection( destPara.getUrl(), destPara.getUsername(),destPara.getPassword());

           connformax= DriverManager.getConnection( destPara.getUrl(), destPara.getUsername(),destPara.getPassword());

        }

        //捕获加载驱动程序异常

        catch ( ClassNotFoundException cnfex ) {

           System.err.println( "装载 JDBC/ODBC 驱动程序失败。" );

           cnfex.printStackTrace();

           System.exit( 1 );  // terminate program

        } catch ( SQLException ex )

        {

            System.err.println( "连接失败" );

            ex.printStackTrace();

            System.exit( 1 );  // terminate program

        }           

    }
    public void copyproduct()

    {

        Statement st=null;

        ResultSet rset=null;

        String sqlstr;

        try {

           //执行SQL语句

           String query = "select * from production";

           st = src.createStatement();

           rset = st.executeQuery(query);          

           int pid,ljid,cid,ciid;

           while(rset.next())

           {

           String pnumber=rset.getString(1);

           String ljnumber=rset.getString(2);

             String cnumber=rset.getString(3);

           //插入到产品表

           pid=getIdfromNumber("project","number",pnumber);

           if(pid==0) //插入一条新记录

           {

                pid=getMax("project");//System.out.println(pid);

                sqlstr="Insert into project(id,number) values("+pid+",'"+pnumber+"')";

                execute(destPara,sqlstr);

           }          

           //插入到零件表

           ljid=getIdfromNumber("product","number",ljnumber);

            if(ljid==0) //插入一条新记录

            {

                ljid=getMax("product");

                sqlstr="Insert into product(id,pid,number) values("+ljid+","+pid+",'"+ljnumber+"')";

                execute(destPara,sqlstr);

            }          

           //插入工具表

            cid=getIdfromNumber("componenttype","number",cnumber);

            if(cid==0) //插入一条新记录

            {
                cid=getMax("componenttype");

                sqlstr="Insert into componenttype(id,aid,number) values("+cid+","+ljid+",'"+cnumber+"')";

                execute(destPara,sqlstr);

            }                    
           }
        }
        catch ( SQLException sqlex ) {

           sqlex.printStackTrace();
        }       
    }   

protected boolean alreadyin(String tname,String colname, String value)

    {       

        int result;

        ResultSet rst=null;

        try {

        //执行SQL语句

        String query = "select "+colname+" from "+tname+" where "+colname+"='"+value+"'";

        Statement statement = connformax.createStatement();

        rst = statement.executeQuery( query );

        if(rst.next())

        {

            statement.close();

            rst.close();

            return true;

        }       

     }

     catch ( SQLException sqlex ) {

        sqlex.printStackTrace();

        return false;

     }

     return false;     

    }


     protected int getIdfromNumber(String tname,String colname, String value)

    {       

        int result;

        ResultSet rst=null;

        try {

        Connection conn= DriverManager.getConnection( destPara.getUrl(), destPara.getUsername(),destPara.getPassword());

        String query = "select id,"+colname+" from "+tname+" where "+colname+"='"+value+"'";

        System.out.println(query);

        Statement statement = conn.createStatement();

        rst = statement.executeQuery( query );

        if(rst.next())

        {

            return rst.getInt("id");

        }  

     }

     catch ( SQLException sqlex ) {

        sqlex.printStackTrace();

        return 0;

     }

     return 0;     

    }

    /**

     * 得到某个表中的最大的id号

     */


     protected int getMax(String tname)

    {       

        int result;

        ResultSet rst=null;    

        try {

        //执行SQL语句

        String query = "select Max(id) from "+tname;

        Statement statement = connformax.createStatement();

        rst = statement.executeQuery( query );

        if(rst.next())

        {

            return rst.getInt(1)+1;

        }

     }

     catch ( SQLException sqlex ) {

        sqlex.printStackTrace();

        return 0;

     }

     return 1;     

    }

    /**

     * 执行某一段sql语句

     */

    public static void execute(ConnPara connpara,String stmt) throws SQLException


     {

        Connection conn=null;

        PreparedStatement ps = null;

        try {

            conn=DriverManager.getConnection( connpara.getUrl(),  connpara.getUsername(), connpara.getPassword());

            System.out.println(stmt);

            ps = conn.prepareStatement(stmt);

            ps.executeUpdate();

        } catch (Exception e) {

            e.printStackTrace();

            System.out.println(e.getMessage());

        } finally {

        if (ps!=null) ps.close();

        if (conn!=null)conn.close();

        }

    }

    public static void main(String argc[])

    {

        DbInput copydb=new DbInput();

        copydb.dbInit();

        copydb.copyproduct();   

    }   

}


  问题:

  1) access数据库不能直接由jdbc读写,解决办法是先把access配置在ODBC中,然后再通过ODBC来操作access数据库。

  2) 执行时找不到com.microsoft.jdbc.sqlserver.SQLServerDriver类,这是因为在运行这个类时,要下载微软的jdbc包,
  
  这个包中有三个文件: msbase.jar,mssqlserver.jar,msutil.jar,把这三个文件包含进去,就不会有问题了。


这个是原作者的完整教程,我在测试的时候发现loadDocument()类中有2个异常,导致程序无法正常的运行!希望高手指点一二!!!!!!!


--  作者:wawehi
--  发布时间:6/2/2005 3:37:00 PM

--  
希望各位大侠指正
--  作者:chinagaox
--  发布时间:6/3/2005 11:33:00 AM

--  
微软的jdbc包?这个包是sun公司的包呀,你到sun的网站下去吧
连接access数据,这是jdbd-odbc连接桥,什么都不下也可以呀
--  作者:315zxl
--  发布时间:8/5/2005 4:44:00 PM

--  
java 程序现在怎么看不太懂了
  如果事。net的还行
--  作者:qlq2001
--  发布时间:8/19/2005 2:07:00 PM

--  
试试找一下JAVA相应的类包。
--  作者:nmgyjw
--  发布时间:12/21/2005 8:43:00 AM

--  
哦,好呀!下去好好研究一下。
W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
93.750ms