我正在努力让我们系统的 java bean 在通过数据库运行查询时能够使用 SQL IN 子句,但遇到了一个令人困惑的问题。
我正在以下通用模式中为 PreparedStatement 构建 SQL 查询:
select [column names]
from [table name]
where [a column name] IN (?, ? , ?, ..., ?)
...,表示任意数量的 ?,具体取决于用户决定在 IN 子句中构建的值的数量。我运行一个循环将它们放入查询字符串中。
从这里开始,我使用 PreparedStatement 的 setString( idx, String ) 方法,并遍历值列表并从索引 1 - # of values 开始运行。
PreparedStatement 通过 executeQuery() 方法运行查询,返回的 ResultSet 似乎不正确。
在使用 4 个值的特定实例中,当我将 PreparedStatement 中的查询转换为 SQL 并替换每个 ? 使用“ ”中的确切值,我得到 3 个结果(因为其中一个值故意不在数据库中)。
另一方面,ResultSet 在其集合中只有 1 行,并且该行始终对应于第一行?IN 子句中的参数。
我什至尝试用 ([column name] = ? OR [column name] = ? ... OR column name] = ?) 伪造 IN 子句,但同样的问题也发生在这里。
有什么想法吗?顺便说一下,连接到 Oracle 数据库。
日志:
2010-02-10 11:16:28,505 DEBUG basic.BasicCursor - Preparing statement SELECT MERCHANT_ID, M_NAME, M_AUTHEN, M_ADMIN_AUTHEN, M_CONTACT_ADDR, M_PAYMENT_ADDR, M_HAS_MPROXY, M_DISABLED, M_FREETEXT, TXN_ID, M_TAX_NAME, M_TAX_RATE, MERCHANT_PARENT_ID, MERCHANT_ROOT_ID, RESERVED_1, RESERVED_2, RESERVED_3, RESERVED_4, EMAIL, LOGICAL_TYPE, CHANNEL_MASK FROM MERCHANT0 WHERE MERCHANT_ID IN (?, ?, ?, ?) ORDER BY MERCHANT_ID
2010-02-10 11:16:28,505 DEBUG basic.BasicCursor - Adding string to slot 1: 6172222222
2010-02-10 11:16:28,505 DEBUG basic.BasicCursor - Adding string to slot 2: 6177740603
2010-02-10 11:16:28,505 DEBUG basic.BasicCursor - Adding string to slot 3: 6177740602
2010-02-10 11:16:28,505 DEBUG basic.BasicCursor - Adding string to slot 4: 6172441111
2010-02-10 11:16:28,512 DEBUG basic.BasicCursor - scanCursor() calling... checking for next row. Current row is : 0
2010-02-10 11:16:28,512 DEBUG basic.BasicCursor - scanCursor() called, hit
2010-02-10 11:16:28,512 DEBUG basic.BasicCursor - scanCursor() got object 6172222222
2010-02-10 11:16:28,512 DEBUG basic.BasicCursor - scanCursor() calling... checking for next row. Current row is : 1
2010-02-10 11:16:28,512 DEBUG basic.BasicCursor - scanCursor() called, not hit
2010-02-10 11:16:28,505 DEBUG basic.BasicCursor - The size of variables list = 4
编辑:发现 PreparedStatement 的问题。我会把它作为练习留给那些好奇想弄清楚的人。它在上面的日志语句中可见。不幸的是,现在我的问题已经级联到我们拥有的一些烦人的专有代码,这些代码将现在预期的 ResultSet 中的行限制为无论如何只显示 1 条记录。叹