简体   繁体   English

如何验证sql查询语法?

[英]How to validate sql query syntax?

java 1.4 Sql server 2000 java 1.4 Sql server 2000

i am taking input of sql query (for validation of field value against values retrieved by executing sql query) from admin user which will be stored in database and later i will executing sql query corresponding to field.Before inserting sql query in database i want to validate its syntax in java code. 我正在从管理员用户输入sql查询(用于验证字段值对执行sql查询检索的值),这将存储在数据库中,之后我将执行对应于field的sql查询。在数据库中插入sql查询之前我想要在java代码中验证其语法。

Fields         Sql Query

stateCode      select statecode from states
district code  select district code from districts

Create a PreparedStatement with the query string; 使用查询字符串创建PreparedStatement ; if this works, the query string is ok (but nothing is executed yet) 如果这样可行,查询字符串就可以了(但还没有执行)

dont think there is any (easy) way to validate sql 不要认为有任何(简单)方法来验证SQL

Sql syntax is complex and allows for alot of different ways to enter a statement. Sql语法很复杂,允许使用很多不同的方法来输入语句。

Think you best shot would be to just execute the sql statent and if you have a SQl exception see if its a bad syntax thats causing it. 认为你最好的方法是只执行sql statent,如果你有一个SQl异常,看看它是否是导致它的错误语法。

you can prepend some sql to avoid from actually executing the query 你可以预先添加一些sql以避免实际执行查询

in sybase it would be SET NOEXEC ON 在sybase中它将是SET NOEXEC ON

Why would you let them enter whole sql-statements? 你为什么要让他们输入整个sql语句?

Just provide to fields and let them enter either the statecode or the districtcode. 只需提供给字段,让他们输入州代码或区号。

Then check if the entered value is a number. 然后检查输入的值是否为数字。 And run the appropriate query with the entered value. 并使用输入的值运行相应的查询。

A possible solution would could be to get the explain plan of the query, if it manages to explain the query I guess it must be valid. 一个可能的解决方案是获取查询的解释计划,如果它设法解释查询我想它必须是有效的。 Down side is that it won't like parametrised queries. 缺点是它不喜欢参数化查询。

You could do SET FMTONLY ON and then execute the query and see if it works. 您可以执行SET FMTONLY ON然后执行查询并查看它是否有效。 Just remember to do SET FMTONLY OFF in a finally block, since it's a connection-level setting. 只记得在finally块中执行SET FMTONLY OFF,因为它是连接级别设置。

You may need a full SQL Parser to do such a vendor-specific offline SQL syntax check. 您可能需要完整的SQL Parser才能执行此类供应商特定的脱机SQL语法检查。

Take a look at this demo which including some Java and C# code: 看一下这个包含一些Java和C#代码的演示

http://www.dpriver.com/blog/list-of-demos-illustrate-how-to-use-general-sql-parser/vendor-specific-offline-sql-syntax-check/ http://www.dpriver.com/blog/list-of-demos-illustrate-how-to-use-general-sql-parser/vendor-specific-offline-sql-syntax-check/

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

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