
在许多业务场景中,我们经常需要从数据库中检索出多条记录,并对这些记录进行逐一处理,例如发送批量通知邮件。然而,在实际开发中,开发者可能会遇到仅能处理查询结果集(resultset)中第一条记录的问题。本教程将深入探讨如何正确地从resultset中提取所有查询结果,并将其封装成集合以便后续处理,最终实现对所有查询结果的逐一操作。
原始代码在数据访问层(DAO)中通过getEmail()方法查询数据库,并返回一个ResultSet。私有辅助方法getEmail(ResultSet searchResultSet)负责从ResultSet中提取数据并封装到UserDto对象中。问题在于,尽管ResultSet可能包含多条记录,但该辅助方法的设计目标是返回单个UserDto对象:
// 原始的私有辅助方法
private UserDto getEmail(ResultSet searchResultSet) throws SQLException {
List<UserDto> result = new ArrayList<UserDto>(); // 创建了一个列表
UserDto userDto = null;
while (searchResultSet.next()) { // 遍历ResultSet
userDto = new UserDto();
userDto.setEmailAddress(searchResultSet.getString(1));
result.add(userDto);
}
// 问题:这里只返回了列表中的第一个元素,或者在列表为空时返回null
return result == null ? null : result.size() == 0 ? null : result.get(0);
}这段代码虽然使用了while (searchResultSet.next())循环遍历了所有结果,并将它们添加到了result列表中,但最终却只返回了result.get(0),即列表中的第一个UserDto对象。因此,无论数据库查询返回多少条记录,外部调用方都只能获取到第一个邮箱地址。
要解决这个问题,我们需要对数据访问层的方法进行修改,使其能够返回所有查询到的UserDto对象组成的列表,并在调用方遍历这个列表进行处理。
首先,我们需要调整getEmail()方法及其私有辅助方法,使其返回List<UserDto>类型,而不是单个UserDto。
立即学习“Java免费学习笔记(深入)”;
修改后的数据访问类(例如Delegate类中的方法):
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
// 假设UserDto是一个包含emailAddress属性的简单JavaBean
class UserDto {
private String emailAddress;
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
@Override
public String toString() {
return "UserDto{emailAddress='" + emailAddress + "'}";
}
}
// 假设Delegate类中包含数据库连接和发送通知的方法
public class Delegate {
// 假设这是一个获取数据库连接的辅助方法
private Connection getConnection() throws SQLException {
// 实际应用中应使用连接池
// 示例:DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
throw new UnsupportedOperationException("getConnection() not implemented. Please provide actual DB connection logic.");
}
/**
* 从数据库中获取所有符合条件的邮箱地址列表。
*
* @return 包含所有UserDto对象的列表,每个对象包含一个邮箱地址。
* @throws RuntimeException 如果发生SQL或其他异常。
*/
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();
// 调用私有辅助方法,现在它返回一个List<UserDto>
return extractEmailsFromResultSet(searchResultSet);
} catch (Exception e) {
// 捕获并包装所有异常为RuntimeException
throw new RuntimeException("Error retrieving emails from database", e);
} finally {
// 确保PreparedStatement和Connection资源被关闭
try {
if (searchResultSet != null) searchResultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close(); // 实际应用中,连接池的连接是归还而不是关闭
} catch (SQLException e) {
System.err.println("Error closing database resources: " + e.getMessage());
}
}
}
/**
* 从ResultSet中提取所有邮箱地址并封装到UserDto列表中。
*
* @param searchResultSet 数据库查询结果集。
* @return 包含所有UserDto对象的列表。
* @throws SQLException 如果访问ResultSet发生错误。
*/
private List<UserDto> extractEmailsFromResultSet(ResultSet searchResultSet) throws SQLException {
List<UserDto> result = new ArrayList<>(); // 初始化一个空的UserDto列表
while (searchResultSet.next()) { // 循环遍历ResultSet中的每一行
UserDto userDto = new UserDto(); // 为每一行创建一个新的UserDto对象
// 从当前行获取EMAIL列的值(假设EMAIL是第一列或通过列名获取)
userDto.setEmailAddress(searchResultSet.getString("EMAIL")); // 推荐使用列名获取
// userDto.setEmailAddress(searchResultSet.getString(1)); // 或者使用列索引
result.add(userDto); // 将UserDto添加到列表中
}
return result; // 返回包含所有UserDto的列表
}
/**
* 模拟发送通知邮件的方法。
*
* @param from 发件人。
* @param subject 邮件主题。
* @param toEmail 收件人邮箱。
* @param ccEmail 抄送人邮箱。
* @param bccEmail 密送人邮箱。
* @param attachmentPath 附件路径。
* @param body 邮件正文。
*/
public void sendNotification(String from, String subject, String toEmail, String ccEmail,
String bccEmail, String attachmentPath, String body) {
System.out.println("Sending email from: " + from + ", to: " + toEmail + ", subject: " + subject);
System.out.println("Body: " + body);
// 实际邮件发送逻辑
}
}关键修改点:
现在,当Delegate.ѻ中的getEmail()方法返回一个List<UserDto>时,我们可以在业务逻辑层(例如第二个类)中轻松地遍历这个列表,并对每个邮箱地址执行发送通知的操作。
调用方类中的代码:
public class NotificationService {
public static void main(String[] args) {
Delegate delegate = new Delegate(); // 实例化Delegate类
try {
// 调用修改后的getEmail方法,现在它返回一个UserDto列表
List<UserDto> users = delegate.getEmail();
if (users != null && !users.isEmpty()) {
// 遍历获取到的所有UserDto对象
for (UserDto userDto : users) {
String toEmail = userDto.getEmailAddress(); // 获取当前UserDto的邮箱地址
// 为每个邮箱地址发送通知
delegate.sendNotification(
"noreply@example.com", // 发件人
"Important Update", // 邮件主题
toEmail, // 收件人
"", // 抄送
"", // 密送
"", // 附件路径
"Dear user, this is an important update for you." // 邮件正文
);
}
System.out.println("All notifications sent successfully.");
} else {
System.out.println("No email addresses found to send notifications.");
}
} catch (RuntimeException e) {
System.err.println("Failed to send notifications: " + e.getMessage());
e.printStackTrace();
}
}
}关键修改点:
通过上述修改,我们成功地将数据库查询结果集中的所有邮箱地址提取出来,并逐一进行了处理。这个解决方案的核心在于:
注意事项:
遵循这些最佳实践,可以确保您的Java应用程序能够高效、健壮地处理数据库中的多条查询结果。
以上就是Java中从ResultSet提取并处理多个查询结果的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号