如何使用jdbc从db2读取xml列

时间:2010-12-15 14:49:29

标签: xml jdbc db2

我们假设我有一个名为ABC的表,其中包含2列id(数字),DB2中的内容(xml)。

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
}

我已经尝试过rs.getObject(i),rs.getString(i)和rs.getSQLXML(i).getString()但没有运气......我只需要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);
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); 
}

希望这会有所帮助......

1 个答案:

答案 0 :(得分:1)

XML行作为大对象实现。尝试rs.getClob(i),然后调用getSubstring从中检索xml。 Here's an example.

相关问题