1. 功能介绍

如果要对SQL做各种统计,通常需要对SQL进行参数化再做统计。比如:

  1. // 原始SQL
  2. select * from t where id = 1
  3. select * from t where id = 2
  4.  
  5. // 参数化SQL
  6. select * from t where id = ?

2. SQL参数化

2.1 SQL参数化API

  1. package com.alibaba.druid.sql.visitor;
  2.  
  3. public class ParameterizedOutputVisitorUtils {
  4. public static String parameterize(String sql, String dbType);
  5. }

2.2 SQL参数化DEMO

  1. import com.alibaba.druid.sql.visitor.ParameterizedOutputVisitorUtils;
  2.  
  3. final String dbType = JdbcConstants.MYSQL;
  4.  
  5. String sql = "select * from t where id = 1 or id = 2 or id = 3";
  6. String psql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType);
  7. assertEquals("SELECT *\n" +
  8. "FROM t\n" +
  9. "WHERE id = ?", psql);

3. 获取具体参数化后的常量值

  1. final String dbType = JdbcConstants.MYSQL;
  2.  
  3. // 参数化SQL是输出的参数保存在这个List中
  4. List<Object> outParameters = new ArrayList<Object>();
  5.  
  6. String sql = "select * from t where id = 101 and age = 102 or name = 'wenshao'";
  7. String psql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType, outParameters);
  8. assertEquals("SELECT *\n" +
  9. "FROM t\n" +
  10. "WHERE id = ?\n" +
  11. "\tAND age = ?\n" +
  12. "\tOR name = ?", psql);
  13.  
  14. assertEquals(3, outParameters.size());
  15. assertEquals(101, outParameters.get(0));
  16. assertEquals(102, outParameters.get(1));
  17. assertEquals("wenshao", outParameters.get(2));