2014-09-29 32 views
1

這是我的查詢。如何填寫PreparedStatement中的WHERE IN參數

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) 
+1

發佈例外。 – proulxs 2014-09-29 17:37:17

+0

@proulxs編輯 – MariaH 2014-09-29 17:42:25

+0

沒有數組超出界限異常嗎?!! – 2014-09-29 17:43:54

回答

0

SQLFeatureNotSupportedException被拋出時:

的JDBC驅動程序不支持此數據類型

,因此長相就像你的數據庫不支持一樣數據類型。

1

JDBC準備語句IN子句僅支持具有已知數量的參數,每個值必須在原始查詢表示:

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

參數設置就像使用statement.setXXX方法的任何其他參數。如果您需要可變數量的參數,則必須動態生成查詢字符串(在IN子句中提供正確數量的?)。

另請參閱:PreparedStatement IN clause alternatives?