Using Prepared Statements to set Table Name

后端 未结 7 1951
生来不讨喜
生来不讨喜 2020-11-22 11:57

I\'m trying to use prepared statements to set a table name to select data from, but I keep getting an error when I execute the query.

The error and sample code is di

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 12:17

    If you need a solution which is not vulnerable to SQL injection, you have to duplicate the query for all tables you need:

    final static String QUERIES = {
        "SELECT x FROM Table1 x WHERE a=:a AND b=:b AND ...",
        "SELECT x FROM Table2 x WHERE a=:a AND b=:b AND ...",
        "SELECT x FROM Table3 x WHERE a=:a AND b=:b AND ...",
        ...
    };
    

    And yes: the queries are duplicates and only the table name differs.

    Now you simply select the query that fits your table, e.g. like

    ...
    PreparedStatement st = conn.prepareStatement(QUERIES[index]);
    ...
    

    You can use this approach wich JPA, Hibernate, whatever...

    If you want a more verbose approach consider using an enum like

    enum AQuery {
        Table1("SELECT x FROM Table1 x WHERE a=:a AND b=:b AND ..."),
        Table2("SELECT x FROM Table2 x WHERE a=:a AND b=:b AND ..."),
        Table3("SELECT x FROM Table3 x WHERE a=:a AND b=:b AND ..."),
        ...
    
        private final String query;
        AQuery(final String query) {
            this.query = query;
        }
    
        public String getQuery() {
            return query;
        }
    }
    

    Now use the either an index

    String sql = AQuery.values()[index].getQuery();
    PreparedStatement st = conn.prepareStatement(sql);
    ...
    

    Or use a table name

    String sql = AQuery.valueOf("Table1").getQuery();
    PreparedStatement st = conn.prepareStatement(sql);
    ...
    

提交回复
热议问题