gpt4 book ai didi

java - DBUtils - 使用 ResultSetHandler

转载 作者:行者123 更新时间:2023-12-01 07:37:41 25 4
gpt4 key购买 nike

我正在尝试使用 ResultSetHandler 将学生列表传递给 servlet,但出现以下错误

java.lang.NumberFormatException: For input string: "id"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

Student类中的方法是

          public List<Student> list2() throws SQLException {
Connection connection = null;
List<Student> studentList = null;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/TestDB");
connection = ds.getConnection();

ResultSetHandler h = new ArrayListHandler();

QueryRunner run = new QueryRunner(ds);

String sql = "select student_id, student_name from tbl_student";

studentList = (List<Student>)run.query(sql, h);


}catch(SQLException sqle) {
sqle.printStackTrace();
}

catch(Exception e) {
e.printStackTrace();
}

finally {
DbUtils.closeQuietly(connection);
}

return studentList;
}

我不使用 DButils 的替代方法工作正常。

      public List<Student> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Student> studentList = new ArrayList<Student>();

try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/TestDB");
connection = ds.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery("select student_id, student_name from tbl_student");
while (resultSet.next()) {
Student student = new Student();
student.setId(resultSet.getInt("student_id"));
student.setName(resultSet.getString("student_name"));
studentList.add(student);
}
}catch(SQLException e) {
e.printStackTrace();
}

catch(Exception e) {
e.printStackTrace();
}

finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}

return studentList;
}

我该如何解决这个问题?

最佳答案

我建议您使用 BeanListHandler 从 ResultSet 中获取所有行并将它们转换为 JavaBean 列表,如下所示:

QueryRunner queryRunner = new QueryRunner(dataSource);
ResultSetHandler<List<Student>> resultSetHandler = new BeanListHandler<Student>(Student.class);
List<Student> studentList = queryRunner.query("SELECT student_id, student_name FROM tbl_student", resultSetHandler);

关于java - DBUtils - 使用 ResultSetHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9588034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com