我们可以在一个方法中使用预处理语句使用两个查询

时间:2011-05-20 19:34:53

标签: java jdbc prepared-statement

我们可以在使用预准备语句的同时在一个方法中使用两个查询,我已尝试使用此但无效的列名异常即将到来。

我的代码摘要如下。

    public double getPayroll(){
            ResultSet rs = null;
            ResultSet rs2 = null;
            Connection conn = null;
            PreparedStatement pstmt = null;
            try {
              conn = getDBConnection();
              int employeeId;
              String q1 = "select e_salary,e_house_rent,e_conv_allow,e_id 
                            from employee";
              pstmt = conn.prepareStatement(q1);
              rs = pstmt.executeQuery();
              double dailyPay=0,basicPay=0,payroll2=0;
              int houseRent=0,convAllow=0;
              while (rs.next()) {
                dailyPay = rs.getInt(1)*.03;
                houseRent=rs.getInt(2);
                convAllow=rs.getInt(3);
                employeeId=rs.getInt(4);
              }
              String q2="select att_status from attendance where 
                            e_id=employeeId";
              pstmt = conn.prepareStatement(q2);
              rs2 = pstmt.executeQuery();
              int noOfPresents = 0;
              while(rs2.next()){
                  noOfPresents+=1;
             }    
             basicPay=dailyPay*noOfPresents;
             payroll2+=basicPay+houseRent+convAllow;

              return payroll2;  
            } catch (Exception e) {
              e.printStackTrace();
              return 0.0;
            } finally {
              try {
                rs.close();
                pstmt.close();
                conn.close();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
}

1 个答案:

答案 0 :(得分:1)

您的问题是q2中的sql假定有一个名为employeeId的列,但我怀疑您要插入变量employeeId的值。

将其更改为

select att_status from attendance where e_id=?

然后执行

pstmt.setString(1, employeeId);

在执行pstmt.executeQuery();

之前