How do I sanitize SQL without using prepared statements

后端 未结 3 1165
猫巷女王i
猫巷女王i 2020-12-05 19:27

For some sql statements I can\'t use a prepared statment, for instance:

SELECT MAX(AGE) FROM ?

For instance when I want to vary the table.

3条回答
  •  时光取名叫无心
    2020-12-05 20:12

    Not possible. Best what you can do is to use String#format().

    String sql = "SELECT MAX(AGE) FROM %s";
    sql = String.format(sql, tablename);
    

    Note that this doesn't avoid SQL injection risks. If the tablename is a user/client-controlled value, you'd need to sanitize it using String#replaceAll().

    tablename = tablename.replaceAll("[^\\w]", "");
    

    Hope this helps.

    [Edit] I should add: do NOT use this for column values where you can use PreparedStatement for. Just continue using it the usual way for any column values.

    [Edit2] Best would be to not let the user/client be able to enter the tablename the way it want, but better present a dropdown containing all valid tablenames (which you can obtain by DatabaseMetaData#getCatalogs()) in the UI so that the user/client can select it. Don't forget to check in the server side if the selection is valid because one could spoof the request parameters.

提交回复
热议问题