【问题标题】:ResultSet Invalid column index结果集无效的列索引
【发布时间】:2022-11-14 19:29:09
【问题描述】:

我有这个错误:原因:java.sql.SQLException:无效的列索引,当我想从结果集中获取电子邮件以便通过在搜索结果中循环发送电子邮件并逐一获取一封电子邮件时。

public List<UserDto> getEmail() {
    
    Connection connection = null;
    
    PreparedStatement preparedStatement = null;
    
    ResultSet searchResultSet = null;
    
    try {
    
        connection = getConnection();
    
        preparedStatement = connection.prepareStatement(
                        "SELECT EMAIL FROM USER WHERE USER.U_SEQ IN ('1','650')");
                
        searchResultSet = preparedStatement.executeQuery();
    
        return getEmail(searchResultSet);
    
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            preparedStatement.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}


private List<UserDto> getEmail(ResultSet searchResultSet) throws SQLException {
    List<UserDto> result = new ArrayList<UserDto >();

    UserDto userDto = null;
    int index = 1;
    while (searchResultSet.next()) {
        userDto = new UserDto();

        userDto .setEmailAddress(searchResultSet.getString(index));
        result.add(userDto);
        index++;
     }
     return result;
}

我调用 getEmail 方法的第二类:

Delegate delegate = new Delegate();

UserDto userDto = new UserDto();

List<UserDto> users = delegate.getEmail();

delegate.sendNotification("****", "****", users .toString(), "", "",
                   "", body);


【问题讨论】:

  • 你试过 index = 0 吗??
  • @Sobhan 不,这些索引是基于 1 的,而不是基于 0 的。见here
  • 您阅读的每条记录似乎都在增加index。如果结果多于列,您将收到此错误。
  • 你为什么在你的循环中做index++;?那条线没有意义。您总是希望选择 SQL 将返回的第一个也是唯一的列

标签: java jdbc resultset sqlexception


【解决方案1】:

失败出现在 getEmail() 函数中。

为什么要增加索引值?

索引变量是列索引,而不是行索引。

您在 while 循环中使用 .next() 遍历结果集。

保持索引值为 1,永远不要改变它!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多