这是我的问题:
我的问题是我有 dc
作为一个变量,如果这个变量为空,那么应该执行 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
并绑定(bind)参数(否则您的代码容易受到 SQL 注入(inject)攻击),此外我将从构建查询开始。所以,类似 -
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();
}
关于java - if else 之后 rs.next() 出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25615583/