我正在将一些jdbc代码从MySql转换为SQL Server。在尝试
时 query = "Update ReportSetup "
+ "set N_ID=?, "
+ "R_Default=?, "
+ "R_Name=?, "
+ "R_Module=? "
+ " where R_ID = ?";
}
PreparedStatement stmt =
(PreparedStatement) con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, ri.getNodeID());
stmt.setInt(2, (ri.isDefault()) ? 1 : 0);
stmt.setString(3, ri.getName());
Object o = ri.getReportModule();
stmt.setObject(4, o);
最后一个语句stmt.setObject(4,o)
抛出异常。
ri.getReportModule returns an instance of a class which implements Externalizable.
该类的writeExternal()方法实现为
public final void writeExternal(final ObjectOutput objectOutput) throws IOException {
for (int i=0; i<pdV.size(); i++) {
PropertyDescriptor pd = pdV.elementAt(i);
try {
Method m = pd.getReadMethod();
Object val = pd.getReadMethod().invoke(this);
System.out.print("writing property " + i + ": " + pd.getName() + " = " + val);
objectOutput.writeObject(val);
} catch (Exception e) {
e.printStackTrace();
}
}
}
有问题的数据库列定义为 varbinary(max),not null
使用MySql可以很好地运行代码,但我无法弄清楚如何使用Sql Server运行它。
非常感谢任何建议
答案 0 :(得分:2)
问题是sql server不乐意保存序列化(就像实现externalizable时那样)。 .setObject()失败。解决方案是使用setBinaryStream()。
// Sql Server can't do an stmt.setObject(4,o) "Conversion from UNKNOWN to UNKNOWN not supported"
// Serialize the object to an output stream and then read it in again into the stmt.
Object o = ri.getReportModule();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream objectOutput = new ObjectOutputStream(bos);
objectOutput.writeObject(o);
objectOutput.flush();
InputStream objectInput = new ByteArrayInputStream(bos.toByteArray());
stmt.setBinaryStream(4, objectInput);
干杯 基督教