0

我正在使用 JdbcTemplate 查询数据库,但是我正在构建一个动态 WHERE 子句并且我想转义引号。下面是我的字符串外观的示例:

有时它们不会是任何 where 子句,因为用户可能想要返回所有记录。所以在这里使用准备好的语句可能不可行。

Jdbc模板

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;
4

1 回答 1

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++;
}
于 2013-04-20T21:58:06.303 回答