我有一个动态构建的 SQL,以下是查询:
private String constructTownSearchQuery(String country, String stateName,String districtName,String townName) {
StringBuilder statesSearchQuery = new StringBuilder();
statesSearchQuery.append(" select cntry.countryid,cntry.country,sta.stateid,sta.state,dst.districtid,dst.district,twn.townid,twn.town ");
statesSearchQuery.append(" from m_countries as cntry,m_states as sta,m_districts as dst,m_towns as twn ");
statesSearchQuery.append(" where cntry.countryid = sta.countryid ");
statesSearchQuery.append(" and sta.stateid = dst.stateid ");
statesSearchQuery.append(" and twn.districtid=dst.districtid ");
if (!country.equals("")) {
statesSearchQuery.append(" and cntry.country='").append(country).append("' ");
}
if (!stateName.equals("")) {
statesSearchQuery.append(" and sta.state='").append(stateName).append("'");
}
if (!districtName.equals("") ) {
statesSearchQuery.append(" and dst.district='").append(districtName).append("'");
}
if (!townName.equals("") ) {
statesSearchQuery.append(" and twn.town='").append(townName).append("'");
}
statesSearchQuery.append(" order by cntry.country ");
return statesSearchQuery.toString();
}
当我使用这个查询时,它很容易发生 SQL 注入,我被告知PreparedStatement
要避免这种情况。
请建议我如何使用preparedStatement
它。
问候。