日期:2014-05-16  浏览次数:20530 次

得PreparedStatement向数据库提交的SQL语句

/**

?* 获得PreparedStatement向数据库提交的SQL语句

?*

?* @param sql:带占位符?的原始sql

?* @param params:参数数组

?* @return:要执行的sql语句

?*/

public static String getPreparedSQL(String sql, Object[] params) {

???????

????????// 1 如果没有参数,说明是不是动态SQL语句

??????? int paramNum = 0;

??????? if (null != params)

?????????????? paramNum = params.length;

?????? if (1 > paramNum)

????????????? return sql;

?

????????// 2 如果有参数,则是动态SQL语句

?????? StringBuffer returnSQL = new StringBuffer();

?

?????? String[] subSQL = sql.split("\\?");

?

?????? for (int i = 0; i < paramNum; i++) {

????????????? if (params[i] instanceof Integer) {

???????????????????? returnSQL.append(subSQL[i]).append(" ").append(params[i]) .append(" ");

????????????? } else if (params[i] instanceof Date) {

???????????????????? returnSQL.append(subSQL[i]).append(" '").append( DateUtils.strDateFormat((java.util.Date) params[i])) .append("' ");

????????????? } else {

???????????????????? returnSQL.append(subSQL[i]).append(" '").append(params[i]) .append("' ");

????????????? }

}