【问题标题】:SQL injection - how to use preparedstatement in javaSQL注入——如何在java中使用preparedstatement
【发布时间】:2012-11-13 15:28:35
【问题描述】:

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

问候。

【问题讨论】:

  • 跟随教程here
  • @JimGarrison,我也使用了preparedstatement,但在我的情况下,它涉及构建查询动态如何完成这是我的问题。
  • 投反对票的人很好,因为他们没有对此发表任何评论。

标签: java prepared-statement sql-injection


【解决方案1】:

当您将 value 参数添加到像 (.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

【讨论】:

  • 感谢 Quoi,我已经看过 SWASP,我的问题是,如果我有一个变量,正如你所展示的那样绑定更好,但我有多个,而运行时只有我知道我得到的变量是什么构造查询,那么怎么做呢?
  • 因为你可以在运行时创建查询,你也可以在运行时设置值,但条件
  • 感谢您的回复,但如果您能在您的回答中提供一些示例,它真的会对我有所帮助。
  • 看到你会像 - if (!country.equals("")) { statesSearchQuery.append(" and cntry.country=?"); } and so on... 这样构建你的查询,而你的 PreparedStatement 将是 - String selectStatement = "SELECT * FROM User WHERE userId = ? "; PreparedStatement prepStmt = con.prepareStatement(selectStatement); if (!country.equals("")){ prepStmt.seString(country);}...
猜你喜欢
  • 2016-11-16
  • 2014-05-30
  • 2017-09-03
  • 2021-08-21
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多