欢迎来到 提示词 博客网站!

【AI】提示词优化:缩短提问长度但不降低效果的5个技巧

来源:提示词资讯 / 时间:2025-11-05

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class EmployeeDAO {
// 查询员工信息并返回列表(按Java 8规范优化)
public List queryEmployees() {
// 初始化集合,使用Java 8钻石运算符简化
List employeeList = new ArrayList<>();
// 定义数据库资源,放在try外部以便finally关闭
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 1. 获取数据库连接(实际项目中建议用连接池,此处为简化示例)
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp_db", "root", "123456");
// 2. 使用PreparedStatement避免SQL注入,预编译SQL
String sql = "select * from employee";
pstmt = conn.prepareStatement(sql);
// 3. 执行查询,获取结果集
rs = pstmt.executeQuery();
// 4. 遍历结果集,封装员工对象
while (rs.next()) {
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setDept(rs.getString("dept"));
emp.setSalary(rs.getDouble("salary"));
employeeList.add(emp);
}
} catch (SQLException e) {
// 捕获SQL异常,打印日志(实际项目建议用日志框架,此处简化)
e.printStackTrace();
} finally {
// 5. 关闭资源,按ResultSet→PreparedStatement→Connection顺序关闭
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return employeeList;
}
}
在线客服
微信联系
客服
扫码加微信
电话咨询
返回顶部