0

我正在将一些 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),而不是 null

该代码使用 MySql 运行良好,但我不知道如何使其与 Sql Server 一起运行。

任何建议将不胜感激

4

1 回答 1

2

问题是 sql server 不乐意保存序列化(如实现可外部化时所做的那样)。.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);

干杯基督徒

于 2013-09-02T22:00:12.587 回答