【问题标题】:How to fill WHERE IN parameter in PreparedStatementPreparedStatement中如何填写WHERE IN参数
【发布时间】:2014-11-24 04:24:20
【问题描述】:

这是我的问题。

String SELECT_USERS_FROM_GROUPS = "select * from user where group_id in ?";

我需要从列表中的组中选择用户:

例如,列表可能是。

long[] groupIdList = { 1, 2 };

这是我的代码:

public List<User> getUsersFromGroups(long[] groupIdList) {

        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        List<User> userList = null;
        User user;

        try {

            connection = Connector.getConnection();
            statement = connection.prepareStatement(SELECT_USERS_FROM_GROUPS);

            Array groupIdArray = connection.createArrayOf("LONG", groupIdList);
            statement.setArray(1, groupIdArray);

            rs = statement.executeQuery();

            userList = new ArrayList<User>();
            while (rs.next()) {
                user = new User();    
                user = fillUser(rs);    
                userList.add(user);
            }

        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        } finally {
            ResourcesUtil.release(rs, statement, connection);
        }

        return userList;

    }

但我在尝试行时遇到异常:Array groupIdArray = connection.createArrayOf("LONG", groupIdList);

有人可以帮助我纠正错误,或指导另一种可能的解决方案。 谢谢;

-- 编辑

例外:

ERROR UserDao:138 - 
java.sql.SQLFeatureNotSupportedException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at com.mysql.jdbc.SQLError.notImplemented(SQLError.java:1350)
    at com.mysql.jdbc.JDBC4Connection.createArrayOf(JDBC4Connection.java:55)
    at com.mchange.v2.c3p0.impl.NewProxyConnection.createArrayOf(NewProxyConnection.java:589)
    at com.thehuxley.data.dao.UserDao.getUsersFromGroups(UserDao.java:120)

【问题讨论】:

  • 没有数组超出边界异常?!!
  • 此异常表示数据库或驱动程序不支持此功能。
  • 您使用的是哪个数据库/驱动程序?我熟悉的大多数数据库都以某种形式支持“Long”类型。 createArrayOf 的第一个参数是数据库识别的 SQL 类型名称,因此您可能只需要更改您传递的第一个参数。
  • 您使用的是哪个 dbm? mysql 不支持数组,按照stackoverflow.com/questions/17842211/… 见第二个答案的解决方案。
  • 我尝试将 LONG 更改为 BIGINT。它也没有工作。 @strwils

标签: java prepared-statement where-in


【解决方案1】:

JDBCprepared statements 仅支持具有已知数量参数的 IN 子句,每个值必须在原始查询中表示:

select * from user where group_id in (?, ?)

参数的设置与使用 statement.setXXX 方法的任何其他参数一样。如果您需要可变数量的参数,则必须动态生成查询字符串(在 IN 子句中提供正确数量的 ?)。

另请参阅:PreparedStatement IN clause alternatives?

【讨论】:

    【解决方案2】:

    SQLFeatureNotSupportedException 在以下情况下被抛出:

    JDBC 驱动不支持这种数据类型

    看来您的数据库不支持"LONG" 数据类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2012-06-17
      • 2011-03-07
      • 2011-06-09
      • 2011-03-23
      • 1970-01-01
      相关资源
      最近更新 更多