转为单列查询语句
@param sql
@return
499023
public static String toSingleColumnSql(String sql) {
		String tempSql = sql.trim();
		String regex = "(?i)^select(.*?)from";
		Matcher m = Pattern.compile(regex).matcher(tempSql);
		String columnAlias = SqlTemplate.SINGLE_COLUMN_ALIAS;
		if (m.find()) {
			columnAlias = m.group(1).trim().replaceAll("\\(\\s+", "(").replaceAll("\\s+\\)", ")").split("\\s+")[0]+ " AS " + columnAlias;
		}
		return tempSql.replaceFirst(regex, "select " + columnAlias + " from ");
	}
970381
public boolean execute(Sql sql) throws SQLException {
		
		long start =  System.currentTimeMillis();
		
		if (sql.validate() == false) {
			return false;
		}
		
		boolean result = false;
		
		PreparedStatement stmt = null;
		try {
			stmt = this.createStatment(conn, sql);
			stmt.execute();
			
			result = true;
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (stmt != null && stmt.isClosed() == false) {
					stmt.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
		
		logger.debug(String.format("Execute %s used %d ms", sql.getSql(), System.currentTimeMillis() - start));

		return result;
	}
611657
public String sql() {
        if (sb == null) {
            throw new AbacusException("This SQLBuilder has been closed after sql() was called previously");
        }

        init(true);

        String sql = null;

        try {
            sql = sb.toString();
        } finally {
            Objectory.recycle(sb);
            sb = null;

            activeStringBuilderCounter.decrementAndGet();
        }

        if (logger.isDebugEnabled()) {
            logger.debug(sql);
        }

        return sql;
    }
1087748
protected int jdbcExecuteUpdate(String sql, Object... args) {
		log(sql);
		long start = System.currentTimeMillis();
		int rows = jdbcTemplate.update(sql.toString(), args);// 此处可以用jdbcTemplate，因为没有in (?)表达式
		long cost = System.currentTimeMillis() - start;
		logSlow(cost, sql, args == null ? new ArrayList<Object>() : Arrays.asList(args));
		return rows;
	}
1127610
public int insert(String sql) {
        String msId = msUtils.insert(sql);
        return sqlSession.insert(msId);
    }
1185511
public Set<String> getTable(String sql) {
		Set<String> tableSet = new HashSet<String>();
		
		try {
			Statement statement = parserManager.parse(new StringReader(sql));
			
			if (statement instanceof Select) {
				tableSet = new SelectParser().parse((Select)statement);
			} else if (statement instanceof Delete) {
				tableSet = new DeleteParser().parse((Delete)statement);
			} else if (statement instanceof Insert) {
				tableSet = new InsertParser().parse((Insert)statement);
			} else if (statement instanceof Update) {
				tableSet = new UpdateParser().parse((Update)statement);
			} else if (statement instanceof CreateTable) {
				tableSet = new CreateTableParser().parse((CreateTable)statement);
			} else if (statement instanceof CreateView) {
				tableSet = new CreateViewParser().parse((CreateView)statement);
			} else if (statement instanceof Alter) {
				tableSet = new AlterParser().parse((Alter)statement);
			} else if (statement instanceof Drop) {
				tableSet = new DropParser().parse((Drop)statement);
			}
		} catch (Exception e) {
			logger.debug(String.format("SQL Parse Exception: exception=%s, sql=%s", e.getMessage(), sql));
		} catch (Error e) {
			logger.debug(String.format("SQL Parse Exception: exception=%s, sql=%s", e.getMessage(), sql));
		}
		
		Set<String> resultSet = new HashSet<String>();
		for (String tableName : tableSet) {
			if (StringUtils.isNotEmpty(tableName)) {
				if (tableName.startsWith("`")) {
					tableName = tableName.substring(1);
				}
				if (tableName.endsWith("`")) {
					tableName = tableName.substring(0, tableName.length() - 1);
				}
				resultSet.add(tableName.toUpperCase());
			}
		}
		
		return resultSet;
	}
791273
public static String converToOrderBySql(String sql, String orderBy) {
        //解析SQL
        Statement stmt = null;
        try {
            stmt = CCJSqlParserUtil.parse(sql);
            Select select = (Select) stmt;
            SelectBody selectBody = select.getSelectBody();
            //处理body-去最外层order by
            List<OrderByElement> orderByElements = extraOrderBy(selectBody);
            String defaultOrderBy = PlainSelect.orderByToString(orderByElements);
            if (defaultOrderBy.indexOf('?') != -1) {
                throw new PageException("原SQL[" + sql + "]中的order by包含参数，因此不能使用OrderBy插件进行修改!");
            }
            //新的sql
            sql = select.toString();
        } catch (Throwable e) {
            throw new PageException("处理排序失败: " + e, e);
        }
        return sql + " order by " + orderBy;
    }
527184
@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> List<T> list(String sql, Object[] params, Class<T> clazz) {
		
		//call jdbcTemplate to query for result
		List<T> list = null;
		if (params == null || params.length == 0) {
			list = getProxy().query(sql, new BeanPropertyRowMapper(clazz));
		} else {
			list = getProxy().query(sql, params, new BeanPropertyRowMapper(clazz));
		}
		
		//return list
		return list;
	}
1284121
private static ProcessedInput processSqlStatement(final String sql) {
        Map<String, String> parsedSqlResult = new HashMap<String, String>();

        Set<String> namedParameters = new HashSet<String>();
        String sqlToUse = sql;
        List<ParameterHolder> parameterList = new ArrayList<ParameterHolder>();

        char[] statement = sql.toCharArray();
        int namedParameterCount = 0;
        int unnamedParameterCount = 0;
        int totalParameterCount = 0;

        int escapes = 0;
        int i = 0;
        while (i < statement.length) {
            int skipToPosition = i;
            while (i < statement.length) {
                skipToPosition = skipCommentsAndQuotes(statement, i);
                if (i == skipToPosition) {
                    break;
                } else {
                    i = skipToPosition;
                }
            }
            if (i >= statement.length) {
                break;
            }
            char c = statement[i];
            if (c == ':' || c == '&') {
                int j = i + 1;
                if (j < statement.length && statement[j] == ':' && c == ':') {
                    // Postgres-style "::" casting operator - to be skipped.
                    i = i + 2;
                    continue;
                }
                String parameter = null;
                if (j < statement.length && c == ':' && statement[j] == '{') {
                    // :{x} style parameter
                    while (j < statement.length && !('}' == statement[j])) {
                        j++;
                        if (':' == statement[j] || '{' == statement[j]) {
                            throw new IllegalArgumentException("Parameter name contains invalid character '"
                                    + statement[j] + "' at position " + i + " in statement " + sql);
                        }
                    }
                    if (j >= statement.length) {
                        throw new IllegalArgumentException("Non-terminated named parameter declaration at position "
                                + i + " in statement " + sql);
                    }
                    if (j - i > 3) {
                        parameter = sql.substring(i + 2, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter);
                    }
                    j++;
                } else {
                    while (j < statement.length && !isParameterSeparator(statement[j])) {
                        j++;
                    }
                    if (j - i > 1) {
                        parameter = sql.substring(i + 1, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter);
                    }
                }
                i = j - 1;
            } else {
                if (c == '\\') {
                    int j = i + 1;
                    if (j < statement.length && statement[j] == ':') {
                        // this is an escaped : and should be skipped
                        sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1);
                        escapes++;
                        i = i + 2;
                        continue;
                    }
                }
                if (c == '?') {
                    unnamedParameterCount++;
                    totalParameterCount++;
                }
            }
            i++;
        }
        ProcessedInput processedInput = new ProcessedInput(sql);

        for (ParameterHolder ph : parameterList) {
            processedInput.addParameter(ph.getParameterName(), ph.getStartIndex(), ph.getEndIndex());
        }

        return processedInput;
    }
681601
public static String getSQL(String sql, StatementParameter param) {
		int i = 0;
		while (sql.indexOf('?') > -1) {
			if (param == null) {
				throw new InvalidParamDataAccessException("没有设置参数.");
			}
			if (i >= param.size()) {
				return sql;
			}
			Class<?> type = param.getType(i);
			Object obj = param.getObject(i);
			String value = getValue(type, obj);
			sql = sql.substring(0, sql.indexOf('?')) + value + sql.substring(sql.indexOf('?') + 1, sql.length());
			i++;
		}
		return sql;//
	}
481000
public String getSmartCountSql(String sql, String name) {
        //解析SQL
        Statement stmt = null;
        //特殊sql不需要去掉order by时，使用注释前缀
        if(sql.indexOf(KEEP_ORDERBY) >= 0){
            return getSimpleCountSql(sql);
        }
        try {
            stmt = CCJSqlParserUtil.parse(sql);
        } catch (Throwable e) {
            //无法解析的用一般方法返回count语句
            return getSimpleCountSql(sql);
        }
        Select select = (Select) stmt;
        SelectBody selectBody = select.getSelectBody();
        try {
            //处理body-去order by
            processSelectBody(selectBody);
        } catch (Exception e) {
            //当 sql 包含 group by 时，不去除 order by
            return getSimpleCountSql(sql);
        }
        //处理with-去order by
        processWithItemsList(select.getWithItemsList());
        //处理为count查询
        sqlToCount(select, name);
        String result = select.toString();
        return result;
    }
543182
public Object[] call(Sql sql) throws SQLException {
		
		long start =  System.currentTimeMillis();
		
		if (sql.validate() == false) {
			return null;
		}
		
		List<Object> result = new ArrayList<Object>();
		
		Statement stmt = null;
		try {
			stmt = this.createStatment(conn, sql);
			if (stmt instanceof CallableStatement) {
				CallableStatement callStmt = (CallableStatement)stmt;
				callStmt.execute();
				List<Object> tmpResults = this.getProcedureOutValue(callStmt, sql);
				for (Object tmpResult : tmpResults) {
					if (tmpResult instanceof ResultSet) {
						result.add(getResultSet((ResultSet)tmpResult));
					} else {
						result.add(tmpResult);
					}
				}
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (stmt != null && stmt.isClosed() == false) {
					stmt.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
		
		logger.debug(String.format("Execute %s used %d ms", sql.getSql(), System.currentTimeMillis() - start));
		
		return result.toArray();
	}
1258733
public <T extends Object, O extends Object> List<T> findBySQL(String sql, List<O> params, RowMapper<T> mapper) {

        if (sql == null) {
            recordLog(" param sql is null!");
        }

        // 构造参数
        Object[] args = null;
        if (params == null) {
            args = new Object[0];
        } else {
            args = params.toArray(new Object[params.size()]);
        }

        // 查询
        if (params != null) {
            recordLog(sql + "\t" + params.toString());
        } else {
            recordLog(sql);
        }
        return (List<T>) jdbcTemplate.query(sql, args, mapper);
    }
630323
public String getSimpleCountSql(final String sql, String name) {
        StringBuilder stringBuilder = new StringBuilder(sql.length() + 40);
        stringBuilder.append("select count(");
        stringBuilder.append(name);
        stringBuilder.append(") from (");
        stringBuilder.append(sql);
        stringBuilder.append(") tmp_count");
        return stringBuilder.toString();
    }
195543
public int countBySQL(String sql, List<?> params) {
        Object[] args = null;
        if (params == null) {
            args = new Object[0];
        } else {
            args = params.toArray(new Object[params.size()]);
        }
        return jdbcTemplate.queryForObject(sql, Integer.class, args);
    }
899998
@SuppressWarnings("unchecked")
    public <N extends Object> List<N> findOneColumn(String sql, List<?> params, final int mapperColumnIndex) {

        if (sql == null) {
            recordLog(" param sql is null!");
        }

        // 查询
        return findBySQL(sql, params, new RowMapper<N>() {
            public N mapRow(ResultSet rs, int count) throws SQLException {
                return (N) (rs.getObject(mapperColumnIndex));
            }
        });
    }
127503
public static String checkCompatibilityIssues( String sql ) {
        sql = sql.replaceAll("LONG PRIMARY KEY AUTOINCREMENT", "INTEGER PRIMARY KEY AUTOINCREMENT");
        sql = sql.replaceAll("AUTO_INCREMENT", "AUTOINCREMENT");
        return sql;
    }