简体   繁体   English

在JavaScript中验证SQL WHERE子句

[英]Validate a SQL WHERE Clause in javascript

How can I validate a string and know if it is a valid SQL where clause. 我如何验证字符串并知道它是否是有效的SQL where子句。 Ex of invalid string: WHERE 1=1 AND EMPRESA = 'CMIP' AND CD_MAQ ==="jjj" Ex of valid string : WHERE 1=1 AND EMPRESA = 'CMIP' AND CD_MAQ ="jjj" 无效字符串的示例: WHERE 1=1 AND EMPRESA = 'CMIP' AND CD_MAQ ==="jjj"无效字符串的示例: WHERE 1=1 AND EMPRESA = 'CMIP' AND CD_MAQ ="jjj"

Appreciate your help. 感谢您的帮助。

Sorry you cannot do this easily... Unless you fancy writing a SQL Parser in Javascript. 抱歉,您不能轻易做到这一点……除非您喜欢用Java编写SQL解析器。

One solution would be to post the query to a backend which runs it in a try catch block and returns if there was an error or not. 一种解决方案是将查询发布到后端,该后端在try catch块中运行该查询,然后返回是否存在错误。

I dread to think what the regex/rules list for this validation would be doing it manually. 我害怕认为此验证的正则表达式/规则列表将是手动执行的操作。

Why do you want to do this?? 为什么要这样做? Explain your actual goal rather than your suggested solution and we can maybe come up with a better idea... If you are passing a WHERE clause to SQL from a search page as you suggest - this is not the correct way to do it... 说明您的实际目标,而不是建议的解决方案,我们可能会想出一个更好的主意...如果您按照您的建议将WHERE子句从搜索页传递到SQL,则这不是正确的方法。 。

Please use Parameterized queries instead. 请改用参数化查询。

Also read up on SQL Injection: What is SQL injection? 另请阅读SQL注入: 什么是SQL注入?

This is a complicated problem, you're essentially wanting to do is write an SQL interpreter. 这是一个复杂的问题,您实际上想要做的是编写一个SQL解释器。 Obviously these already exist (on database systems of course) but also there are libraries that can do this for you. 显然,这些已经存在(当然,在数据库系统上),但是也有一些库可以为您做到这一点。 For Javascript see: 对于Javascript,请参阅:

https://github.com/forward/sql-parser https://github.com/forward/sql-parser

Although, you probably don't want to perform security critical validation only on the client side, although it won't hurt to do it there and then also validate in on the server side before running it (if that is the end goal). 虽然,您可能不想只在客户端执行安全性至关重要的验证,尽管这样做并不会伤害您,然后再在服务器端进行验证,然后再运行它(如果这样做是最终目标),则不会受到任何损害。

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

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