现在XML数据库大行其道,特别在数据交换领域,由于XML数据库本身的特点,可以大显身手,那么JDBC如何来操作XMLDB呢,我们举几个简单的例子抛砖引玉一下吧
- 在数据库中获取XMLType类型的列值,比如存储过程返回XmlType等,代码如下:
public static String getOracleXMlType2String(Object obj){
try{
if(obj instanceof OPAQUE){
StringBuffer sb = new StringBuffer();
OPAQUE op =(OPAQUE)obj;
if(op!=null){
XMLType poxml = XMLType.createXML(op);
if(poxml!=null){
sb.append(poxml.getStringVal());
}
}
return sb.toString();
}
return obj.toString();
}catch(Exception ex){
return null;
}
}
执行存储过程代码:
Object[] res = DbUtils.ExecuteSP("{call 存储过程名(?,?)}", new Object[]{
new SpParameter(Types.VARCHAR, "IN", "in参数", "in参数值")
,new SpParameter(OracleTypes.OPAQUE,"OUT","x",null)}, conn);
select x.sys_nc_rowinfo$.getclobval() as column_value from xmltypeTable
public static final Object[] ExecuteSP(String stmt, Object[] inparams,
Connection connection) {
int i = 1;
CallableStatement st = null;
SpParameter sp = null;
SpParameter outp = null;
int DataType;
String Direction;
String Name;
String DataValue;
try {
st = connection.prepareCall(stmt);
int oupcount = 0;
for (i = 0; i < inparams.length; i++) {
if (inparams[i] instanceof SpParameter) {
sp = (SpParameter) inparams[i];
if (sp.GetDirection().toUpperCase().equals("IN")) {
switch (sp.GetDataType()) {
case Types.FLOAT:
case Types.INTEGER:
st
.setLong(i + 1, Long.parseLong(sp
.GetDataValue()));
break;
case Types.DATE:
st.setDate(i + 1, java.sql.Date.valueOf(sp
.GetDataValue()));
break;
case Types.SQLXML:
st.setSQLXML(i + 1, null);
break;
default:
st.setString(i + 1, sp.GetDataValue());
break;
}
} else {
if(sp.getDataType() == OracleTypes.OPAQUE){
st.registerOutParameter (i+1, OracleTypes.OPAQUE,"SYS.XMLTYPE");
}else
st.registerOutParameter(i + 1, sp.GetDataType());
oupcount = oupcount + 1;
}
} else
st.setObject(i + 1, inparams[i]);
}
st.execute();
i = 1;
if (oupcount > 0) {
Object[] outps = new Object[oupcount];
int j = 0;
for (i = 0; i < inparams.length; i++) {
if (!(inparams[i] instanceof SpParameter))
continue;
sp = (SpParameter) inparams[i];
if (!sp.GetDirection().toUpperCase().equals("IN")) {
DataType = sp.GetDataType();
Direction = sp.GetDirection();
Name = sp.GetName();
switch (DataType) {
case Types.FLOAT:
DataValue = String.valueOf(st.getLong(i + 1));
break;
case Types.INTEGER:
DataValue = String.valueOf(st.getInt(i + 1));
break;
case Types.DATE:
DataValue = st.getDate(i + 1).toString();
break;
case OracleTypes.OPAQUE:
DataValue = getOracleXMlType2String(st.getObject(i+1));
break;
default:
DataValue = st.getString(i + 1);
break;
}
sp.setDataValue(DataValue);
outps[j++] = DataValue;
// res.addElement(new SpParameter(DataType, Direction,
// Name,
// DataValue));
}
}
return outps;
} else {
return null;
}
} catch (SQLException ex) {
} finally {
if (st != null) {
try {
st.close();
} catch (Exception ex) {
log.error(ex);
}
}
}
}
已有 0 人发表留言,猛击->>这里<<-参与讨论
JavaEye推荐