我正在使用JdbcTemplate来查询数据库,但我正在构建一个动态WHERE子句,我想要转义引号。 Under是我的字符串外观的一个示例:
有些时候它们不会是任何where子句,因为用户可能想要返回所有记录。所以在这里使用预备声明可能不可行。
的JdbcTemplate
String sql = "select crime.*, "+
"criminalSocialSecurityNumber,criminal.fName as criminalFName,criminal.lName as criminalLName,"+
"criminal.photo as criminalPhoto,criminal.dob as criminalDob,victimSocialSecurityNumber,"+
"victim.fName as victimFName,victim.lName as victimLName,victim.photo as victimPhoto, victim.dob as victimDob "+
"from tblcrimes crime "+
"left join tblcriminalcrime on crime.crimeRecNo = tblcriminalcrime.crimeRecNo "+
"left join tblvictimcrime on crime.crimeRecNo = tblvictimcrime.crimeRecNo "+
"inner join tblcitizens criminal on criminal.socialSecurityNumber = tblcriminalcrime.criminalSocialSecurityNumber "+
"inner join tblcitizens victim on victim.socialSecurityNumber = tblvictimcrime.victimSocialSecurityNumber " + where_clause;
答案 0 :(得分:2)
使用预准备语句是完全可能的,也是你应该做的。
使用占位符(?
)为每个参数动态构建查询,每次添加占位符时,还要将参数值添加到参数列表中。最后,您有一个参数化的SQL查询,以及一个要绑定到预准备语句的参数值列表。
像
这样的东西List<Object> args = new ArrayList<Object>();
StringBuilder whereClause = new StringBuilder();
if (criteria.getFoo() != null) {
whereClause.append(" and foo = ?");
args.add(criteria.getFoo());
}
if (criteria.getBar() != null) {
whereClause.append(" and bar = ?");
args.add(criteria.getBar());
}
// ...
PreparedStatement stmt = connection.prepareStatement(query + whereClause);
int i = 1;
for (Object arg : args) {
stmt.setObject(i, arg);
i++;
}