求高手给个sql语句书写
public Employee FindEmployee(String userName, Connection conn)
throws MyException {
Employee emp = null;
String sql = "select * from Employee where UserName = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, userName);
rs = ps.executeQuery();
while (rs.next()) {
emp = new Employee();
emp.setEmployeeNo(rs.getString("EmployeeNo"));
emp.setUserName(rs.getString("UserName"));
emp.setPassWord(rs.getString("PassWord"));
emp.setRoleID(rs.getString("RoleID"));
emp.setName(rs.getString("Name"));
emp.setIDNumber(rs.getString("IDNumber"));
emp.setBirthday(rs.getDate("Birthday"));
emp.setGender(rs.getString("Gender"));
emp.setStatus(rs.getString("Status"));
emp.setDepartmentID(rs.getString("DepartmentID"));
emp.setEmployeeFrom(rs.getDate("EmployeeFrom"));
emp.setEmployeeTo(rs.getDate("EmployeeTo"));
}
} catch (
SQLException e) {
throw new MyException("通过用户名查找用户失败", e);
} finally {
DBUtil.close(rs);
DBUtil.close(ps);
}
return emp;
}
这个方法是通过用户名查询对象,假如我需要通过身份证号IDNumber查询对象或者其他字段查询,写一个通用的方法,我是这样写的,但是领导说sql语句不能采用拼接的方式,我无语了。。。如果传入2个问号,那第一个问号代表类型,那最后的sql语句将变成select * from Employee where “type”=?最后查询失败,不能用StringBulider进行拼接,求高手给个解决方法。
public Employee FindEmployee(String type,String value, Connection conn)
throws MyException {
Employee emp = null;
String sql = "select * from Employee where" +type+"= ?";
//............
}
------解决方案--------------------
可以用String.format吗?
for example
Java code
public Employee FindEmployee(String filedName, String fieldValue, Connection conn)
String sql = String.format("select * from Employee where %s = ?", fieldName);
ps = conn.prepareStatement(sql);
ps.setString(1, fieldValue);
rs = ps.executeQuery();
------解决方案--------------------
没,我看你最开始说的是这个效果吧:
String sql = "select * from Employee where UserName = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, userName);
这个才不算是拼接。
其它什么字符串直接++、StringBuffer、format啥都,都算是拼接,所以:
String sql = "select * from Employee where " +type+" = ?"; 这个必然算拼接。
不过我认为你可以跟你老板探讨下,消除拼接的目的是什么;如果非不用拼接的话,如何实现通用性。我三楼主要探讨的内容是这个。