这是我的问题:我的问题是,我有dc
作为一个变量,如果这个变量为null,那么应该执行else部分。但这里的条件是,当执行if()部分时,它不进入if(rs.next())
?为什么?当我的dc值为2时,rs.next()
工作,但当它为1时,它不工作。
if (dc != null) {
rs = st.executeQuery("select e.env_id,s.* from env_mast e inner join"
+ " db_server_mast s on e.dc_id=s.dc_id join cust_mast c on "
+ "e.cust_id=c.cust_id where cust_name='" + env + "' and "
+ "e.dc_id='" + dc + "' ");
} else {
System.out.println("Not DC");
rs = st.executeQuery("select e.env_id,s.* from env_mast e inner join "
+ "db_server_mast s on e.dc_id=s.dc_id join cust_mast c on "
+ "e.cust_id=c.cust_id where cust_name='" + env + "' ");
}
if (rs.next()) {
}
我真的建议您使用PreapredStatement
和绑定参数(否则您的代码容易受到sql注入攻击),此外,我将从构建查询开始。所以,类似的东西
String sql = "select e.env_id,s.* from env_mast e inner join "
+ "db_server_mast s on e.dc_id=s.dc_id join cust_mast c on "
+ "e.cust_id=c.cust_id where cust_name=?"
+ ((dc != null) ? " and e.dc_id=?" : "");
try (PreparedStatement ps = conn.prepareStatement(sql);) {
ps.setString(1, env);
if (dc != null) {
ps.setString(2, dc);
}
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
根据我的理解,您需要先执行if-else
。然后尝试执行另一个与dc = 1
或dc = 2
无关的if-else
如果我没有错的话:
if (rs.next())
只有当dc = 2
时才会执行,所以在我看来,你的代码应该是这样的:
if(dc == null) {
System.out.println("Not DC");
//do something when dc is null
} else {
System.out.println("Is DC");
//do something when the dc is not null
for(int i = 0; i < dc; i ++) {
//something you perform in the if(rs.next()) { }
}
}
首先,在使用Elliot在这个答案中建议的查询时,最好使用prepared语句。如果您仍然想使用语句,那么您最好更改以下方法,以避免混淆并更好地维护代码。
String selectQuery = "select e.env_id,s.* from env_mast e inner join"
+ " db_server_mast s on e.dc_id=s.dc_id join cust_mast c on "
+ "e.cust_id=c.cust_id where cust_name='" + env + "' ";
if (dc != null)
{
selectQuery += " and "
+ "e.dc_id='" + dc + "' ";
}
rs = st.executeQuery (selectQuery);
if (rs.next())
{
....
}
对于您的问题,
- 当
dc = 1
时,表env_mast中可能没有记录 - 如果
dc = 2
,则表env_mast具有记录
检查您的表格数据。