- Notifications
You must be signed in to change notification settings - Fork 8.6k
SQL_Parser_Parameterize
温绍 edited this page Oct 15, 2017 · 6 revisions
如果要对SQL做各种统计,通常需要对SQL进行参数化再做统计。比如:
// 原始SQL select*from t where id =1select*from t where id =2// 参数化SQL select*from t where id = ?packagecom.alibaba.druid.sql.visitor; publicclassParameterizedOutputVisitorUtils{publicstaticStringparameterize(Stringsql, StringdbType)}importcom.alibaba.druid.sql.visitor.ParameterizedOutputVisitorUtils; finalStringdbType = JdbcConstants.MYSQL; Stringsql = "select * from t where id = 1 or id = 2 or id = 3"; Stringpsql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType); assertEquals("SELECT *\n" + "FROM t\n" + "WHERE id = ?", psql);finalStringdbType = JdbcConstants.MYSQL; // 参数化SQL是输出的参数保存在这个List中List<Object> outParameters = newArrayList<Object>(); Stringsql = "select * from t where id = 101 and age = 102 or name = 'wenshao'"; Stringpsql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType, outParameters); assertEquals("SELECT *\n" + "FROM t\n" + "WHERE id = ?\n" + "\tAND age = ?\n" + "\tOR name = ?", psql); assertEquals(3, outParameters.size()); assertEquals(101, outParameters.get(0)); assertEquals(102, outParameters.get(1)); assertEquals("wenshao", outParameters.get(2));