我是J2EE应用程序的新手,在尝试通过学生ID(也是我的主键)搜索数据库后,尝试显示数据库中的记录。 jdbc / studentDB是我的JNDI名称 在studentdao.java中我的语法@Resource(name =“jdbc / studentDB”)是否足够用于连接?如果是,问题是方法executeFetchQuery(int id)吗? 我出错的地方请帮忙。
//search.java(servlet)
ResultSet rs = ***studentDao.executeFetchQuery(v);***
String fName = null;
try{
fName = rs.getString("firstname");
while(rs.next()){
fName = rs.getString("firstname");
}
}catch (Exception ex){
System.out.println("error: "+ex);
}
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet getdata</title>");
out.println("</head>");
out.println("<body>");
out.println("fname: "+ fName);
out.println("</body>");
out.println("</html>");
// studentdao.java
//required imports
@Stateless
public class StudentDao implements StudentDaoLocal {
@Resource(name="jdbc/studentDB")
private DataSource datasource;
@PersistenceContext
private EntityManager em;
@Override
public void addStudent(Student student) {
em.persist(student);
}
@Override
public void editStudent(Student student) {
em.merge(student);
}
@Override
public void deleteStudent(int studentId) {
em.remove(getStudent(studentId));
}
@Override
public Student getStudent(int studentId) {
return em.find(Student.class, studentId);
}
@Override
public List<Student> getAllStudents() {
return em.createNamedQuery("Student.getAll").getResultList();
}
/**
*
* @param id
* @return
*/
@Override
***public ResultSet executeFetchQuery(int id){***
ResultSet rs = null;
try{
Connection conn = datasource.getConnection();
String sql = "SELECT * FROM STUDENT WHERE STUDENTID = '" + id +"'";
rs = conn.createStatement().executeQuery(sql);
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
return rs;
}
//输出数据库中的id
fname:null
答案 0 :(得分:0)
以下始终会导致异常,因为您在rs.next()之前调用rs.getString()
<强>更新强>
在StudentDao.executeFetchQuery(int)
中,您将返回ResultSet
,但用于获取Connection
的{{1}}已关闭,因此ResultSet
也将关闭。
这不是正确的方法。从[{1}}返回ResultSet
所以它应该是。
firstname
并在StudentDao.executeFetchQuery(int)
public String executeFetchQuery(int id){
String firstname = null;
try{
Connection conn = datasource.getConnection();
String sql = "SELECT * FROM STUDENT WHERE STUDENTID = '" + id +"'";
rs = conn.createStatement().executeQuery(sql);
if(rs.next()){
firstName = rs.getString("firstname");
}
conn.close();
}catch (Exception e) {
System.err.println(e.getMessage());
}
return firstname;
}