需要执行mysql中的一段脚本,获取具体的值.然后将这段sql拼入到sql中.
//需要执行的脚本 if('aa@sohu.com'='', 1=1, cus.buyer_email like '%aa@sohu.com%')
处理方式.
1. 先将 条件,返回结果1,返回结果2 截取出来.
2. 再将放到javascript中,运行一下.
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Compilable compilable = (Compilable) engine;
Bindings bindings = engine.createBindings(); // println(op1);
String script = "function exeSql(op1,res1,res2){ if(eval(op1)){return res1;}else{return res2;}} exeSql(op1,res1,res2);"; //定义函数并调用
CompiledScript JSFunction = compilable.compile(script); //解析编译脚本函数
bindings.put("op1","'aa@sohu.com'=='aa@sohu.com'");
bindings.put("res1", "1=1");
bindings.put("res2", "cus.buyer_email like '%aa@sohu.com%'");
Object result = JSFunction.eval(bindings);
System.out.println(result); //调用缓存着的脚本函数对象,Bindings作为参数容器传入
结果就出来了.
js中的eval作用非常大,将我传入的字符串,转化为需要执行的脚本语言了.很强大.
//需要执行的脚本 if('aa@sohu.com'='', 1=1, cus.buyer_email like '%aa@sohu.com%')
处理方式.
1. 先将 条件,返回结果1,返回结果2 截取出来.
2. 再将放到javascript中,运行一下.
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Compilable compilable = (Compilable) engine;
Bindings bindings = engine.createBindings(); // println(op1);
String script = "function exeSql(op1,res1,res2){ if(eval(op1)){return res1;}else{return res2;}} exeSql(op1,res1,res2);"; //定义函数并调用
CompiledScript JSFunction = compilable.compile(script); //解析编译脚本函数
bindings.put("op1","'aa@sohu.com'=='aa@sohu.com'");
bindings.put("res1", "1=1");
bindings.put("res2", "cus.buyer_email like '%aa@sohu.com%'");
Object result = JSFunction.eval(bindings);
System.out.println(result); //调用缓存着的脚本函数对象,Bindings作为参数容器传入
结果就出来了.
js中的eval作用非常大,将我传入的字符串,转化为需要执行的脚本语言了.很强大.
使用JS执行SQL条件判断
本文介绍了一种利用Java ScriptEngine来执行SQL条件判断的方法,通过解析和编译JavaScript脚本来决定SQL语句的走向。这种方法可以灵活地处理动态生成的SQL语句。
2432

被折叠的 条评论
为什么被折叠?



