zoukankan      html  css  js  c++  java
  • Java操作DB2 XML数据实践

    Java操作DB2 XML数据实践
     
    自学了90分钟的DB2 XQuery,还不很熟悉,就要在项目中用了,心里很不踏实,还是先跑个CRUD的Demo看看,以免走弯路。
     
    代码很粗糙,主要目的是看看JDBC是否能很好的执行这种新SQL,呵呵。
     
    另外,在此之前,看到Oracle老大已经开始实现一个操作XML数据的规范,目前还没有正式出台,希望Sun能尽快跟进,将标准的API接口定出来,以支持广大的Java社区。项目有期限,我们也没时间等Sun给我们做好任何东西,自己动手实现吧。
     
    下面是我做的一个Demo,希望能给正在研究这一块的朋友一点参考,XQuery SQL代码参考了DB2官方文档。
     
    一、实现一个简单的数据库工具
    import java.sql.*;

    /**
    * 简单的数据连接工具
    * File: DBUtils.java
    * User: leizhimin
    * Date: 2008-3-18 15:19:12
    */

    public class DBUtils {
        public static final String url = "jdbc:db2://192.168.3.143:50000/lavasoft";
        public static final String username = "lavasoft";
        public static final String password = "lavasoftdb2";
        public static final String driverClassName = "com.ibm.db2.jcc.DB2Driver";

        /**
         * 获取数据库连接Connection
         *
         * @return 数据库连接Connection
         */

        public static Connection makeConnection() {
            Connection conn = null;
            try {
                Class.forName(driverClassName);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            try {
                conn = DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return conn;
        }

        public static void main(String args[]) {
            testConnection();
        }

        /**
         * 测试连接方法
         */

        public static void testConnection() {
            Connection conn = makeConnection();
            try {
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM DM_HYML");
                while (rs.next()) {
                    String s1 = rs.getString(1);
                    String s2 = rs.getString(2);
                    System.out.println(s1 + s2);
                }
                rs.close();
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
     
    二、写一个简单的测试类执行各种XQuery SQL
     
    import com.topsoft.icib.common.utils.DBUtils;

    import java.sql.*;
    import java.io.ByteArrayInputStream;
    import java.io.InputStream;
    import java.io.IOException;

    /**
    * DB2 XML数据操作测试
    * File: TestXMLDAO.java
    * User: leizhimin
    * Date: 2008-3-18 16:33:51
    */

    public class TestDB2XML {

        /**
         * 预删除表Customer
         *
         * @throws SQLException
         */

        public static void testDropXMLTable() throws SQLException {
            String drop_sql = "DROP TABLE Customer";
            Connection conn = DBUtils.makeConnection();
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(drop_sql);
            stmt.close();
            conn.close();
        }

        /**
         * 创建表
         *
         * @throws SQLException
         */

        public static void testCreateXMLTable() throws SQLException {
            String ct_sql = "CREATE TABLE Customer (Cid BIGINT NOT NULL PRIMARY KEY, Info XML)";
            Connection conn = DBUtils.makeConnection();
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(ct_sql);
            stmt.close();
            conn.close();
        }

        /**
         * 插入数据
         *
         * @throws SQLException
         * @throws IOException
         */

        public static void testInsertXMLTable() throws SQLException, IOException {
            String xml = "<customerinfo xmlns="http://posample.org" Cid="1000"> " +
                    "<name>Robert Shoemaker</name> " +
                    "<addr country="Canada"> " +
                    "<street>1596 Baseline</street> " +
                    "<city>zhengzhou</city> " +
                    "<prov-state>Ontario</prov-state> " +
                    "<pcode-zip>N8X 7F8</pcode-zip> " +
                    "</addr> " +
                    "<phone type="work">905-555-2937</phone> " +
                    "</customerinfo>";
            String ins_sql = "INSERT INTO CUSTOMER (CID, INFO) VALUES (1000, ?)";
            Connection conn = DBUtils.makeConnection();
            conn.setAutoCommit(false);
            PreparedStatement pstmt = conn.prepareStatement(ins_sql);
            byte[] b = xml.getBytes();
            InputStream ins = new ByteArrayInputStream(b);
            pstmt.setBinaryStream(1, ins, b.length);
            pstmt.executeUpdate();
            conn.commit();
            ins.close();
            pstmt.close();
            conn.close();
        }

        /**
         * XQuery查询数据
         *
         * @throws SQLException
         */

        public static void testQueryXMLTable() throws SQLException {
            String query_sql = "SELECT XMLQUERY ( " +
                    "'declare default element namespace "http://posample.org"; " +
                    "for $d in $doc/customerinfo " +
                    "return <out>{$d/name}</out>' " +
                    "passing INFO as "doc") " +
                    "FROM Customer as c " +
                    "WHERE XMLEXISTS ('declare default element namespace "http://posample.org"; " +
                    "$i/customerinfo/addr[city="zhengzhou"]' passing c.INFO as "i")";
            Connection conn = DBUtils.makeConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query_sql);
            StringBuffer xmls = new StringBuffer();
            while (rs.next()) {
                xmls.append(rs.getString(1)).append(" ");
            }
            System.out.println(xmls.toString());
            stmt.close();
            conn.close();
        }

        /**
         * XQuery更新数据
         *
         * @throws SQLException
         * @throws IOException
         */

        public static void testUpdateXMLTable() throws SQLException, IOException {
            String xml = "<customerinfo xmlns="http://posample.org" Cid="1002"> " +
                    "<name>Jim Noodle</name> " +
                    "<addr country="Canada"> " +
                    "<street>1150 Maple Drive</street> " +
                    "<city>Newtown</city> " +
                    "<prov-state>Ontario</prov-state> " +
                    "<pcode-zip>Z9Z 2P2</pcode-zip> " +
                    "</addr> " +
                    "<phone type="work">905-555-7258</phone> " +
                    "</customerinfo>";
            String up_sql = "UPDATE customer SET info =?" +
                    "WHERE XMLEXISTS ( " +
                    "'declare default element namespace "http://posample.org"; " +
                    "$doc/customerinfo[@Cid = 1000]' " +
                    "passing INFO as "doc")";

            Connection conn = DBUtils.makeConnection();
            conn.setAutoCommit(false);
            PreparedStatement pstmt = conn.prepareStatement(up_sql);
            byte[] b = xml.getBytes();
            InputStream ins = new ByteArrayInputStream(b);
            pstmt.setBinaryStream(1, ins, b.length);
            pstmt.executeUpdate();
            conn.commit();
            ins.close();
            pstmt.close();
            conn.close();
        }

        /**
         * 查询xml列数据,用于验证
         *
         * @throws SQLException
         */

        public static void testQueryXMLColumn() throws SQLException {
            String query_sql = "SELECT INFO FROM Customer";
            Connection conn = DBUtils.makeConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query_sql);
            StringBuffer xmls = new StringBuffer();
            while (rs.next()) {
                xmls.append(rs.getString(1)).append(" ");
            }
            System.out.println(xmls.toString());
            stmt.close();
            conn.close();
        }

        /**
         * 测试入口,方法组调用
         *
         * @param rags
         * @throws Exception
         */

        public static void main(String rags[]) throws Exception {
            testDropXMLTable();
            testCreateXMLTable();
            testInsertXMLTable();
            testQueryXMLTable();
            testUpdateXMLTable();
            testQueryXMLColumn();
        }
    }
     
    三、运行结果
     
    <out xmlns="http://posample.org"><name>Robert Shoemaker</name></out>

    <customerinfo xmlns="http://posample.org" Cid="1002"><name>Jim Noodle</name><addr country="Canada"><street>1150 Maple Drive</street><city>Newtown</city><prov-state>Ontario</prov-state><pcode-zip>Z9Z 2P2</pcode-zip></addr><phone type="work">905-555-7258</phone></customerinfo>


    Process finished with exit code 0
     
    呵呵,终于看到运行结果了。。。
  • 相关阅读:
    Ajax请求ashx 返回 json 格式数据常见问题
    netbeans 优化设置
    Java基础static的探究
    mybatis中:selectKey返回最近插入记录的id
    Java map 详解
    Statement和PreparedStatement的异同
    css3 @media支持ie8用respond.js 解决IE6~8的响应式布局问题
    apply和call
    兼容性问题:backgroud-size支持IE8浏览器的方法
    json对象和json字符串之间的转化
  • 原文地址:https://www.cnblogs.com/liudianjia/p/12551662.html
Copyright © 2011-2022 走看看