如何使用c#检查SQLquery语法是否有效? [英] How to check SQLquery syntax is valid or not using c# ?

查看:181
本文介绍了如何使用c#检查SQLquery语法是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我正在尝试使用C#进行某种查询优化树.从用户读取任何查询语句,然后对其进行一些操作.但是我不能做的是检查此查询是否有效,换句话说,我想执行类似Sqlsever解析器的方法来检查查询语法而无需连接到SQLserver,因为此查询是虚拟查询,我没有任何表或数据库,我只是在查询中使用它.


注意:我正在使用VS2005
请有人帮忙.

Hi all

I was trying to do some kind of query optimization tree using C# .reading any query statement from user and then do some operations over it. but what i can''t did was to check if this query is valid or not in other words i want to do something like Sqlsever parser to check query syntax without need to connect to SQLserver because this query is virtual query i have not any Tables or DataBases i just working in the query as it .


Note : I am using VS2005
please if any one can help .

Thanks.

推荐答案

如果您有SQL连接,则可以在执行SQL之前使用"SET NOEXEC ON"命令来避免编写SQL解析器.命令.这告诉SQL不要执行任何命令,只是评估它们是否会被执行.
If you have an SQL connection, you can avoid the need to write an SQL parser, by using the "SET NOEXEC ON" command before executing your SQL command. This tells SQL not to execute any commands, just evaluate if they would have been executed.
SqlCommand cmd = new SqlCommand("SET NOEXEC ON", conn);
cmd.ExecuteNonQuery();
cmd = new SqlCommand(sqlToBeChecked, conn);
cmd.ExecuteNonQuery();

如果没有引发异常,一切都很好.

If no exception is thrown, all is fine.


是的,您需要编写一个查询解析器,它将检查SQL规则以检查查询是否看起来像它.的格式正确.因此,您必须考虑SQL查询可以采用的各种形式,保留哪些单词等,并编写规则以解析字符串.您可能可以使用正则表达式至少执行一个简单的版本.
Yes, you need to write a query parser, which would check the rules of SQL to check if a query seems like it''s validly formed. So you''d have to consider the various forms a SQL query can take, what words are reserved, etc, and write rules to parse the string. You can probably use regex to do at least a simple version of this.


这篇关于如何使用c#检查SQLquery语法是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆