如何在不使用预准备语句的情况下清理SQL

编程入门 行业动态 更新时间:2024-10-27 14:30:04
本文介绍了如何在不使用预准备语句的情况下清理SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于某些sql语句,我不能使用准备好的语句,例如:

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

SELECT MAX(AGE) FROM ?

例如,当我想改变表时。是否有一个实用程序可以在Java中清理sql? ruby中有一个。

For instance when I want to vary the table. Is there a utility that sanitizes sql in Java? There is one in ruby.

推荐答案

是的,准备好的语句查询参数只能在你使用单一的地方使用字面值。您不能将参数用于表名,列名,值列表或任何其他SQL语法。

Right, prepared statement query parameters can be used only where you would use a single literal value. You can't use a parameter for a table name, a column name, a list of values, or any other SQL syntax.

因此您必须插入应用程序变量进入SQL字符串并适当地引用字符串。使用引用来分隔您的表名称标识符,并通过加倍来转义引号字符串:

So you have to interpolate your application variable into the SQL string and quote the string appropriately. Do use quoting to delimit your table name identifier, and escape the quote string by doubling it:

java.sql.DatabaseMetaData md = conn.getMetaData(); String q = md.getIdentifierQuoteString(); String sql = "SELECT MAX(AGE) FROM %s%s%s"; sql = String.format(sql, q, tablename.replaceAll(q, q+q), q);

例如,如果您的表名字面上是表name ,并且您的RDBMS标识符引用字符是,然后 sql 应包含如下字符串:

For example, if your table name is literally table"name, and your RDBMS identifier quote character is ", then sql should contain a string like:

SELECT MAX(AGE) FROM "table""name"

我同意@ChssPly76的评论 - 如果你的用户输入实际上不是文字表名,而是你的代码映射成表名的能指,那你最好然后插入到SQL查询中。这可以让您更加确信不会发生SQL注入。

I also agree with @ChssPly76's comment -- it's best if your user input is actually not the literal table name, but a signifier that your code maps into a table name, which you then interpolate into the SQL query. This gives you more assurance that no SQL injection can occur.

HashMap h = new HashMap<String,String>(); /* user-friendly table name maps to actual, ugly table name */ h.put("accounts", "tbl_accounts123"); userTablename = ... /* user input */ if (h.containsKey(userTablename)) { tablename = h.get(userTablename); } else { throw ... /* Exception that user input is invalid */ } String sql = "SELECT MAX(AGE) FROM %s"; /* we know the table names are safe because we wrote them */ sql = String.format(sql, tablename);

更多推荐

如何在不使用预准备语句的情况下清理SQL

本文发布于:2023-11-15 04:25:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591136.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   情况下   如何在   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!