我有一个名为empbeans.java的bean,它调用dao类(userdao.java),用于将数据插入名为emp_leave的表中。它根据从session中带来的ename插入值.i有一个小编码问题。它显示的消息是“抱歉!无法申请离开!”。在userdao.java中是否有任何错误?plz solve。
这是代码。
public void apply(ActionEvent evt) {
ename = util.getSession().getAttribute("ename").toString();
boolean done= userdao.apply(this);
if ( done ) {
reason = "";
leavedate="";
message = "Applied For Leave Successfully!";
}
else
message = "Sorry! Could Not Apply For Leave!";
}
public static boolean apply(empbeans e) {
Connection con = null;
PreparedStatement ps=null;
PreparedStatement ps1=null;
try {
con = Database.getConnection();
ps1=con.prepareStatement("select eid from employee where ename=?");
ps1.setString(1,e.getEname());
ResultSet rs=ps1.executeQuery();
ps = con.prepareStatement(
"insert into emp_leaves values(?,?,?,default)");
ps.setInt(1,rs.getInt(1));
ps.setString(1,e.getLeavedate());
ps.setString(2,e.getReason());
int count = ps.executeUpdate();
return count == 1;
} catch (Exception ex) {
System.out.println("Error in inserting into time sheet -->" + ex.getMessage());
return false;
} finally {
Database.close(con);
}
}
答案 0 :(得分:1)
您错过了rs.next();
。因此,ps.setInt(1,rs.getInt(1));
答案 1 :(得分:0)
我不明白为什么apply方法需要变量evt,而实际上方法从不使用它。
然后请将代码更改为能够理解返回的异常:
<强> userdao.java 强>
public static void apply(empbeans e) throws Exception{
Connection con = null;
PreparedStatement ps=null;
PreparedStatement ps1=null;
try {
con = Database.getConnection();
ps1=con.prepareStatement("select eid from employee where ename=?");
ps1.setString(1,e.getEname());
ResultSet rs=ps1.executeQuery();
ps = con.prepareStatement(
"insert into emp_leaves values(?,?,?,default)");
ps.setInt(1,rs.getInt(1));
ps.setString(1,e.getLeavedate());
ps.setString(2,e.getReason());
int count = ps.executeUpdate();
}catch(Exception e)
{e.printStackTrace(); throw e;}
}
<强> empbeans.java 强>
public void apply(ActionEvent evt) {
String ename = util.getSession().getAttribute("ename").toString();
try{
userdao.apply(this);
reason = "";
leavedate="";
message="Leave applied successfully";
}catch(Exception e)
{
message = "Sorry! Could Not Apply For Leave! reason:"+e.getMessage();
}
}
请记住,错误不会被抛弃。
从这里你可以得到它无法正常工作的确切原因,我猜rs.next()。