我想从SQL查询中获取所有参数.在这种情况下,查询是数组中的纯字符串.
我有以下形式的查询对:
SELECT * FROM my_table t WHERE (t.attr1 = ? AND t.attr2 = ?) OR t.attr3= ?
它的对是(其中包含我要检索的参数):
SELECT * FROM my_table t WHERE (t.attr1 = 3 AND t.attr2 = 'str') OR t.attr3= 4
因此输出将是:
3, 'str' and 4.
如何基于此对检索这些值?
我在Java中尝试使用正则表达式,但是会很困难,因为?可以是数字
字符串等等.该字符串可以包含另一个?这是字符串的一部分,例如:
UPDATE my_table SET attr2 = ? WHERE attr5 = ?
UPDATE my_table SET attr2 = 'Is it true?' WHERE attr5 = 'What is it?'
最佳答案
您可以使用这种方法来做到这一点,在此替换掉每一个?在查询中使用(.*),然后根据它创建一个模式.然后应用另一对具有实际值的字符串,然后打印出将按?动态创建的所有组中的值.存在于查询字符串中.
这是执行相同操作的Java代码.
// This map stores your paired queries where key stores the placeholder query and value stores the query having actual parameters.
Map<String, String> pairMap = new HashMap<>();
pairMap.put("SELECT * FROM my_table t WHERE (t.attr1 = ? AND t.attr2 = ?) OR t.attr3= ?", "SELECT * FROM my_table t WHERE (t.attr1 = 3 AND t.attr2 = 'str') OR t.attr3= 4");
pairMap.put("UPDATE my_table SET attr2 = ? WHERE attr5 = ?", "UPDATE my_table SET attr2 = 'Is it true?' WHERE attr5 = 'What is it?'");
pairMap.forEach((k,v) -> {
System.out.println("For query: "+k);
k = k.replaceAll("([*+^$()\\[\\]{}])", "\\\\$1"); // this escapes all the characters that have special meaning in regex so they get treated as literal characters
k = k.replaceAll("\\?", "(.*)");
Pattern p = Pattern.compile(k);
Matcher m = p.matcher(v);
if (m.matches()) {
for (int i=0;i<m.groupCount();i++) {
System.out.println(m.group(i+1));
}
} else {
System.out.println("Didn't match");
}
System.out.println();
});
哪个打印,
For query: SELECT * FROM my_table t WHERE (t.attr1 = ? AND t.attr2 = ?) OR t.attr3= ?
3
'str'
4
For query: UPDATE my_table SET attr2 = ? WHERE attr5 = ?
'Is it true?'
'What is it?'
如您所见,该代码适用于占位符?的任何可变值.在查询字符串中,并打印配对查询中存在的所有具有实际值的值.