SQL注入 - 如何在java中使用preparedstatement

时间:2012-11-26 06:56:23

标签: java prepared-statement sql-injection

我有一个动态构建的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

问候。

1 个答案:

答案 0 :(得分:3)

当您将值参数添加到查询(例如.append(country))时,它可以很容易地注入。

例如,如果您将国家/地区作为"Australia"通过,这是正常情况,则不会有任何问题,但如果我将国家/地区作为"a' or '1'='1",则会选择您所有的国家/地区。

PreparedStatement SQL语句中进行预编译,然后可以使用此对象多次有效地执行此语句,并且可以安全地进行SQL注入。

更多关于PreparedStatement

String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();

更多关于SQL injection