问题
i have a SQL which is dynamically build,the following is the query :
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();
}
when i used this query it is prone for SQL injection and i was told to use PreparedStatement
to avoid this.
Pleas suggest me how to go about using preparedStatement
for this.
Regards.
回答1:
When you add value parameter to query like (.append(country)
) this then it could be easily inject-able.
For Example if you pass country as "Australia"
which is normal case it would not have any problem but if I pass country as "a' or '1'='1"
, then it will select all your country.
Where as in a PreparedStatement
SQL statement is precompiled and this object can then be used to efficiently execute this statement multiple times and you will be safe from SQL injection.
more on PreparedStatement
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
More on SQL injection.
来源:https://stackoverflow.com/questions/13560021/sql-injection-how-to-use-preparedstatement-in-java