在PreparedStatement中绑定null变量

Pau*_*lin 12 java null jdbc

我发誓这曾经工作,但它不是在这种情况下.我正在尝试匹配col1,col2和col3,即使其中一个或多个为null.我知道在某些语言中我不得不求助于像((? is null AND col1 is null) OR col1 = ?).这需要吗?

        PreparedStatement selStmt = getConn().prepareStatement(
                "SELECT     * " +
                "FROM       tbl1 " +
                "WHERE      col1 = ? AND col2 = ? and col3 = ?");
        try
        {
            int col = 1;
            setInt(selStmt, col++, col1);
            setInt(selStmt, col++, col2);
            setInt(selStmt, col++, col3);
            ResultSet rs = selStmt.executeQuery();
            try
            {
                while (rs.next())
                {
                   // process row
                }
            }
            finally
            {
                rs.close();
            }
        }
        finally
        {
            selStmt.close();
        }

   // Does the equivalient of stmt.setInt(col, i) but preserves nullness.
    protected  static void setInt(PreparedStatement stmt, int col, Integer i)
    throws SQLException
    {
        if (i == null)
            stmt.setNull(col, java.sql.Types.INTEGER);
        else
            stmt.setInt(col, i);
    }
Run Code Online (Sandbox Code Playgroud)

ig0*_*774 9

这可能取决于JDBC驱动程序,但在大多数情况下,是的,您需要使用上面显示的更多扩展形式.

JDBC预处理语句通常是围绕参数化查询的本机实现的相对较薄的包装器,即查询带有?代替参数传递给查询编译器并进行编译,因此,稍后,当您调用stmt.executeQuery()时,语句无法从a调整 column = ?column IS NULL.这不是JDBC的限制,而是SQL中NULL的语义.因为SQL x = NULL未定义x <> NULL.

这就是说,一些JDBC驱动程序可能违反的概念NULL-ity在SQL和允许的setNull()从改造陈述= ?IS NULL,这将是非常不规范的行为(虽然它可以通过编写某种查询的预处理很容易完成方法).