ITPub博客

首页 > 应用开发 > IT综合 > 使用正则表达式检验sql语句(只支持select(不含函数,子查询)) (转)

使用正则表达式检验sql语句(只支持select(不含函数,子查询)) (转)

原创 IT综合 作者:amyz 时间:2007-08-15 12:16:38 0 删除 编辑
使用正则表达式检验sql语句(只支持select(不含函数,子查询)) (转)[@more@]

/**
*本文用到了正则表达式,如果你对正则表达式不熟悉,请查看相应的资料,jdk1.4以上支持正则表达式,具体可以
*参考Java.util.regexp.Pattern里的javadoc(讲的还不错)
*最初发布的时候很仓促,一行注释都没有,实在对不住各位了.
*这个小程序是用来检测sql(select)语句是否合法的,其实主要目的是探讨怎么用正则表达式来表示sql语句.
*由于sql里包含了函数和子查询,这都属于语法分析的范畴,而正则表达式是用来表示词法的,要实现这一点好像比较吃力(lex好像也难),
*所以我决定不再努力去实现这个目标(另外写语法分析程序吧).
to:*@author">*@author xcopy@sina.com
*/
import java.util.*;
import java.text.*;
class sqltest
{
 public static void main(String[] args)
  {
 String span="select aaaa.id  name ,hello ,type t,h from datas aaaa,city b  where a.id=b.id and c like 'e%'  and name is null ";
 span=span.toUpperCase();//测试用sql语句
 System.out.println(span);
 String column="(一列的正则表达式 匹配如 product p
 String columns=column+"(,s*"+column+")*"; //多列正则表达式 匹配如 product p,category c,warehouse w
 String ownerenable="((一列的正则表达式 匹配如 a.product p
 String ownerenables=ownerenable+"(,s*"+ownerenable+")*";//多列正则表达式 匹配如 a.product p,a.category c,b.warehouse w

 String from="FROMs+"+columns;
 String condition="(w+.){0,1}w+s*(=|LIKE|IS)s*'?(w+.){0,1}[w%]+'?";//条件的正则表达式 匹配如 a=b 或 a is b..
 String conditions=condition+"(s+(AND|OR)s*"+condition+"s*)*";//多个条件 匹配如 a=b and c like 'r%' or d is null
 String where="(WHEREs+"+conditions+"){0,1}";
 String pattern="SELECTs+(*"; //匹配最终sql的正则表达式
 System.out.println(pattern);//输出正则表达式
 System.out.println(span.matches(pattern));//是否比配


 }
 }

 

 


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10752019/viewspace-957755/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
  • 博文量
    3982
  • 访问量
    7895691