如何使用 jdbc 从 db2 读取 xml 列 [英] How to read xml column from db2 using jdbc
本文介绍了如何使用 jdbc 从 db2 读取 xml 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个名为 ABC 的表,在 DB2 中有 2 列 id(number), content(xml).
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
}
我已经尝试过 rs.getObject(i)、rs.getString(i) 和 rs.getSQLXML(i).getString() 但没有运气...而且我只需要 db2 解决方案
I have tried rs.getObject(i), rs.getString(i) and rs.getSQLXML(i).getString() but no luck... And I need only db2 solution
我已经修复了自己:
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...
推荐答案
XML 行被实现为大对象.尝试 rs.getClob(i)
,然后调用 getSubstring
以从中检索 xml.这是一个例子.
XML rows are implemented as large objects. Try rs.getClob(i)
, then call getSubstring
to retrieve the xml from it. Here's an example.
这篇关于如何使用 jdbc 从 db2 读取 xml 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文