SQL注入 - 如何在java中使用preparedstatement [英] SQL injection - how to use preparedstatement in java

查看:128
本文介绍了SQL注入 - 如何在java中使用preparedstatement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态构建的SQL,以下是查询:

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();
    }

当我使用此查询时,它很容易被SQL注入,我被告知使用 PreparedStatement 来避免这种情况。

when i used this query it is prone for SQL injection and i was told to use PreparedStatement to avoid this.

请告诉我如何使用 preparedStatement 为此。

Pleas suggest me how to go about using preparedStatement for this.

问候。

推荐答案

当您将值参数添加到查询中时( .append(country)),这可能很容易注入。

When you add value parameter to query like (.append(country)) this then it could be easily inject-able.

例如,如果您将国家/地区作为澳大利亚通过,这是正常情况,它不会有任何问题,但如果我将国家/地区作为a'或'1'='1传递,然后它会选择您所有的国家/地区。

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.

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

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.

更多信息,请访问 PreparedStatement

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

更多关于 SQL注入

这篇关于SQL注入 - 如何在java中使用preparedstatement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆