我想使用用户输入从数据库中获取数据
int fnameNum = 0;
int lnameNum = 0;
int emailNum = 0;
if (firstName != null) {
sb.append(" E.FIRST_NAME = ? ");
fnameNum = 1;
if (email == null) {
sb.append(" AND ");
sb.append(" E.LAST_NAME LIKE ? ");
lnameNum = 2;
} else if (lastName == null) {
sb.append(" AND ");
sb.append(" E.EMAIL = ? ");
emailNum = 2;
} else {
sb.append(" AND ");
sb.append(" E.LAST_NAME LIKE ? ");
lnameNum = 2;
sb.append(" AND ");
sb.append(" E.EMAIL = ? ");
emailNum = 3;
}
}
String sqlString = sb.toString();
preStatement = connection.prepareStatement(sqlString);
if (fnameNum > 0) {
preStatement.setString(fnameNum, firstName);
}
if (lnameNum > 0) {
preStatement.setString(lnameNum, lastName + "%");
}
if (emailNum > 0) {
preStatement.setString(emailNum, email);
}
ResultSet rs = preStatement.executeQuery();
html中有3个文本框。我想根据用户的输入从数据库中获取数据,即使另一个文本框为空白或所有文本框都填充有数据。
答案 0 :(得分:2)
这是使用字符串连接创建SQL语句的最糟糕的主意。这种方法将给您带来很多惩罚/问题。其中一些是:
执行此操作的最佳选择是使用命名参数(如果DBMS系统支持)。请参见下面的示例:
SELECT * from TBL
WHERE (:NAME is null or NAME = :NAME) AND
(:SURNAME is NULL or SURNAME = :SURNAME)