Using a prepared statement and variable bind Order By in Java with JDBC driver

前端 未结 3 1782
情深已故
情深已故 2020-12-01 14:27

I\'m using

  1. jdbcTemplate to make JDBC connections to a mySQL DB
  2. prepared statements to protect myself as much as possible from SQL injection attacks
3条回答
  •  死守一世寂寞
    2020-12-01 14:58

    My suggestion is the mapping of keys and columns. It's a safe solution.

    At the beginning, we initiate our map in the simplest possible way. For convenience, I overloaded the get (Obiect key) method to return the default column ("fullName") in case of failure. This will protect against SqlExeption.

        static Map sortCol;
    {
        sortCol = new HashMap(){
            {//Enter all data for mapping
                put("name","fullName");
                put("rok","year");
                put("rate","likes");
                put("count-rate","countRate");
    
            }
            /**
             * 
             * @param key for column name
             * @return column name otherwise default "fullName"
             */
            @Override
            public String get(Object key) {
                String col =super.get(key);
                return null==col?"fullName":col;
            }
        };
    }
    

    Here is a simple example of use.

    String sqlQuery= "Select \"fullName\",year,likes,count-rate, country ..."+
     "from  blaBla..."+
     "where blaBla..."+
     "order by "+sortCol.get("keySort") "\n"; // keySort can have the value name, count-rate etc .. 
    

    By the way, you should never reveal the real names of columns in user interfaces, such as REST or SOAP etc ... For the attacker, this is a great help.

提交回复
热议问题