Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 11.0.1 (中文) » MobiLink - 入门 » MobiLink 教程 » 教程:与 XML 同步

 

第 4 课:使用 MobiLink 直接行处理创建 Java

在本课中,您将使用直接行处理来处理客户端数据库的 OrderComments 表中的行。为直接行处理添加以下方法:

  • GetUpload   将此方法用于 handle_UploadData 事件。GetUpload 将上载的注释写入 XML 文件中。

以下过程介绍如何创建 Java 类,其中包括用于处理的方法。有关完整列表,请参见完整的 MobiLinkOrders 代码列表 (Java)

♦  为仅下载直接行处理创建 Java 类
  1. 使用 Java 创建名为 MobilinkOrders 的类。

    在文本编辑器或开发环境中键入以下代码:

    //Mobilink imports
    import ianywhere.ml.script.*;
    import java.io.*;
    import java.sql.*;
    
    //XML parser
    import javax.xml.parsers.DocumentBuilder; 
    import javax.xml.parsers.DocumentBuilderFactory;  
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.xml.sax.SAXException;  
    
    //DOM Objects
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    //For writing XML objects
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.dom.DOMSource;  
    import javax.xml.transform.stream.StreamResult; 
    
    public class MobiLinkOrders {
        // ...
    }
  2. 声明一个类级别 DBConnectionContext 实例和文档实例。文档是将 XML 文档作为对象表示的类。

    DBConnectionContext _cc;
     Document _doc;

    MobiLink 服务器会将 DBConnectionContext 实例传递到类构造函数。DBConnectionContext 封装有关与 MobiLink 统一数据库的当前连接的信息。

  3. 创建类构造函数。

    类构造函数设置类级别 DBConnectionContext 实例。

    在文本编辑器或开发环境中键入以下代码:

    public MobiLinkOrders( DBConnectionContext cc ) {
      _cc = cc;
    }
  4. 编写 GetUpload() 方法。

    1. 编写方法声明。

      在文本编辑器或开发环境中键入以下代码:

      // method for the handle_UploadData synchronization event
      public void GetUpload( UploadData ut ) throws SQLException, IOException {
    2. 从 Mobilink 客户端获得任何上载的插入。

      在文本编辑器或开发环境中键入以下代码:

      //  get an UploadedTableData for OrderComments
        UploadedTableData orderCommentsTbl = 
          ut.getUploadedTableByName("OrderComments");
       
        // get inserts uploaded by the MobiLink client
        ResultSet insertResultSet = orderCommentsTbl.getInserts();
    3. 在现有 XML 文件 order_comments.xml 中读取。

      在文本编辑器或开发环境中键入以下代码:

          readDom("order_comments.xml");
    4. 对于每个插入行,将其添加到 XML 文件。

      在文本编辑器或开发环境中键入以下代码:

          // Write out each insert in the XML file
          while( insertResultSet.next() ) {  
            buildXML(insertResultSet);
          }
    5. 编写 XML 文件。

      在文本编辑器或开发环境中键入以下代码:

      writeXML();
    6. 关闭 ResultSet。

      在文本编辑器或开发环境中键入以下代码:

          // Close the result set of uploaded inserts
          insertResultSet.close(); 
  5. 编写 buildXML 方法。

    在文本编辑器或开发环境中键入以下代码:

      private void buildXML( ResultSet rs ) throws SQLException {  
        int order_id = rs.getInt(1);
        int comment_id = rs.getInt(2);
        String order_comment = rs.getString(3);    
    
        //Create the comment object to be added to the XML file
        Element comment = _doc.createElement("comment");
        comment.setAttribute("id", Integer.toString(comment_id));
        comment.appendChild(_doc.createTextNode(order_comment));
    
        //Get the root element (orders)
        Element root = _doc.getDocumentElement();
        
        //get each individual order
        NodeList rootChildren = root.getChildNodes();
        for(int i = 0; i < rootChildren.getLength(); i++) {
          //if the order exists, add the comment to the order      
          Node n = rootChildren.item(i);
          if(n.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element) n;
            int idIntVal = Integer.parseInt(e.getAttribute("id"));
            if(idIntVal == order_id) {
              e.appendChild(comment);
              //The comment has been added to the file, so exit the function
              return;
            }
          }
        }
    
        //if the order did not exist already, create it
        Element order = _doc.createElement("order");
        order.setAttribute("id", Integer.toString(order_id));
        //add the comment to the new order
        order.appendChild(comment);    
        root.appendChild(order);
      }
  6. 编写 writeXML 方法。

    在文本编辑器或开发环境中键入以下代码:

      private void writeXML() {
    
        try {
     
          // Use a Transformer for output
          TransformerFactory tFactory = TransformerFactory.newInstance();
          Transformer transformer = tFactory.newTransformer();
     
          //The XML source is _doc
          DOMSource source = new DOMSource(_doc);
          //write the xml data to order_comments.xml
          StreamResult result = new StreamResult(new File("order_comments.xml"));
          transformer.transform(source, result);
               
        } catch (TransformerConfigurationException tce) {
          // Error generated by the parser
          System.out.println ("\n** Transformer Factory error");
          System.out.println("   " + tce.getMessage() );
    
          // Use the contained exception, if any
          Throwable x = tce;
          if (tce.getException() != null) x = tce.getException();
          x.printStackTrace();
          
        } catch (TransformerException te) {
          // Error generated by the parser
          System.out.println ("\n** Transformation error");
          System.out.println("   " + te.getMessage() );
    
          // Use the contained exception, if any
          Throwable x = te;
          if (te.getException() != null) x = te.getException();
          x.printStackTrace();
               
     }
    
      }
  7. 编写 readDOM 方法。

    在文本编辑器或开发环境中键入以下代码:

      private void readDom(String filename) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          try {
            //parse the Document data into _doc
            DocumentBuilder builder = factory.newDocumentBuilder();
            _doc = builder.parse( new File(filename) );
     
          } catch (SAXException sxe) {
            // Error generated during parsing)
            Exception x = sxe;
            if (sxe.getException() != null) x = sxe.getException();
            x.printStackTrace();
    
          } catch (ParserConfigurationException pce) {
            // Parser with specified options can't be built
            pce.printStackTrace();
    
          } catch (IOException ioe) {
            // I/O error
            ioe.printStackTrace();
          }
    
      }
  8. 将 Java 代码在工作目录 c:\MLobjxml 中保存为 MobiLinkOrders.java

  9. 编译您的类文件。

    1. 浏览到包含 Java 源文件的目录。

    2. 编译 MobiLinkOrders 时引用面向 Java 的 MobiLink 服务器 API 库。

      对于 Java,需要引用位于 install-dir\Java 中的 mlscript.jar。您还需要确保正确安装了 XML DOM 库。运行以下命令来编译 Java 类,用您的 SQL Anywhere 11 目录替换 c:\Program Files\SQL Anywhere 11\

      javac -classpath "c:\Program Files\SQL Anywhere 11\java\mlscript.jar" MobiLinkOrders.java
进一步阅读

有关同步逻辑的详细信息,请参见使用 Java 语言编写同步脚本

有关直接行处理的详细信息,请参见直接行处理


完整的 MobiLinkOrders 代码列表 (Java)