How to read xml column from db2 using jdbc

我的梦境 提交于 2020-01-04 14:01:28

问题


Let us say I have a table called ABC with 2 columns id(number), content(xml) in DB2.

String q="select * from ABC where id=121";
Connection conn = getConnection(dbUrl,schemaName,userName,password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(q);
while(rs.next())
{
   //HERE HOW CAN I GET CONTENT COLUMN VALUE IN STRING FORMAT
}

I have tried rs.getObject(i), rs.getString(i) and rs.getSQLXML(i).getString() but no luck... And I need only db2 solution

I have fixed my self:

String q="select * from ABC where id=121";
Connection conn = getConnection(dbUrl,schemaName,userName,password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(q);
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
   if(rsmd.getColumnTypeName(i).equalsIgnoreCase("XML"))
   {
            convertInStreamToString(rs.getBinaryStream(i));

    }
    else
    {
        rs.getObject(i);
    }
}

private String convertInStreamToString(InputStream data) throws Exception
{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while ((n=data.read(buf))>=0)
        {
           baos.write(buf, 0, n);
        }

        data.close();
        byte[] bytes = baos.toByteArray();
        return new String(bytes); 
}

Hope this helps...


回答1:


XML rows are implemented as large objects. Try rs.getClob(i), then call getSubstring to retrieve the xml from it. Here's an example.



来源:https://stackoverflow.com/questions/4451156/how-to-read-xml-column-from-db2-using-jdbc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!