【发布时间】: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