setObject() method of PreparedStatement

2019-06-14 21:56发布

问题:

Can I use the setObject() method of PreparedStatement for all datatypes (like String, int or double)?

What are the potential problems if I use that?

protected void fillStatement(PreparedStatement stmt, Object[] params)
        throws SQLException {

        if (params == null) {
            return;
        }

        for (int i = 0; i < params.length; i++) {
            if (params[i] != null) {
                stmt.setObject(i + 1, params[i]);
            } else {
                stmt.setNull(i + 1, Types.OTHER);
            }
        }
    }

回答1:

I use setObject() exclusively with MySQL and I've never had a problem with it. I cannot speak for other databases or other vendors.



回答2:

You could potentially have an issue with Blobs or specialized date fields like MSSQL DateTimeOffeet.

Also I found an issue "Unable to convert between java.lang.Character and JAVA_OBJECT."

If the parameter is a single character type.

    if (param instanceof Character) {
        param = "" + param;
    }


标签: java jdbc