简体   繁体   English

在where子句之后从sql查询中提取列名

[英]extract column names from sql query after where clause

I've a requirement where I need to pull out data from database. 我有一个需要从数据库中提取数据的要求。 The query is- 查询是-

SELECT e.Data AS EntityBlob, f.Data AS FpmlBlob 
FROM [Trades.InventoryRecord] ir, EntityBlob e, FpmlBlob f 
WHERE %s AND uid = e.uid AND uid = f.uid

Here %s is the predicate after where clause which user will input from an html form. 这里%s是where子句后面的谓词,用户将从html表单输入该谓词。

User input will be in this form : 用户输入将采用以下形式:
1. TradeDate = ' 2013-04-05 ' AND IsLatest = 'TRUE' 1. TradeDate =' 2013-04-05 IsLatest ='TRUE'
2. StreamId= ' IA0015 ' 2. StreamId =' IA0015 '
3. The query may have IN clause also 3.查询中可能也有IN子句

Now when this query is rendered I get exception ambigous column streamId or ambigous column IsLatest, as these columns exists in more than one table with same name. 现在,呈现此查询时,我得到了异常歧义列streamId或歧义列IsLatest,因为这些列存在于多个具有相同名称的表中。 So to remove this ambiguity I need to modify the query as - ir.IsLatest or ir.StreamId 因此,要消除这种歧义,我需要将查询修改为-ir.IsLatest或ir.StreamId

To do so by java code, I need to first parse the predicate after where clause, extract column names and insert table name alias- 'ir' before each column name so that the query becomes - 要通过Java代码执行此操作,我需要首先在where子句之后解析谓词,提取列名称,并在每个列名称之前插入表名称别名-'ir',以使查询变为-

SELECT e.Data AS EntityBlob, f.Data AS FpmlBlob 
FROM [Trades.InventoryRecord] ir, EntityBlob e, FpmlBlob f 
WHERE ir.TradeDate = '2013-04-05' AND ir.IsLatest = 'TRUE' AND uid = e.uid AND uid = f.uid

what is the best way to parse this predicate, or if there is any other way I can achieve the same result? 解析此谓词的最佳方法是什么,或者是否有其他方法可以实现相同的结果?

My answer to this question is to not parse the user input - there is far too much that can go wrong. 我回答这个问题是不解析用户输入-有太多可能出错。 It would be a lot better to have a UI with drop downs and buttons for selecting equality, inequality, ranges, in statements, etc. It may seem like more work, but protecting yourself from a SQL injection attack is even more. 拥有一个带有下拉菜单和用于选择相等性,不相等性,范围,in语句等的按钮的UI会好得多。这看起来似乎需要更多工作,但保护自己免受SQL注入攻击的影响更大。 And even if you are not concerned about malicious SQL injection, then the user still has to get every thing exactly right, or the statement fails. 即使你不担心恶意的SQL注入,则该用户仍然需要得到每一件事情完全正确,或者语句失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM