我们可以在一种方法中使用准备好的语句来使用两个查询吗
我们可以在使用准备好的语句时在一种方法中使用两个查询吗?我已经尝试使用这个,但即将出现无效列名异常。
我的代码片段如下。
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();
}
}
}
Can we use two queries in one method while using prepared statement, I have tried using this but invalid column name exception is coming.
My code snippets is as follows.
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();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题是q2中的sql假设有一个名为employeeId的列,但我怀疑你想插入变量employeeId的值。
将其更改为
然后
在执行 pstmt.executeQuery() 之前执行;
Your problem is that the sql in q2 assumes that there is a column named employeeId, but I suspect you want to insert the value of the variable employeeId.
Change it to
Then execute
before executing pstmt.executeQuery();