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

JDBC公共操作方法(四):【查询】、【增、删、改】和【调用存储过程】的公共方法 03

?

/**
	 * @Title: callProcedure
	 * @Description: 执行存储过程的公共方法
	 * @param sql
	 *            : 调用存储过程的语句
	 * @param params
	 *            : 条件
	 * @return
	 * @author
	 * @date 2011-12-29
	 */
	public String[] callProcedure(String sql, String[][] params) {

		String[] result = null;

		if (null == sql || "".equals(sql.trim())) {
			LOG.error("The sql is null, return.");
			return result;
		}

		// 获取数据库连接
		Connection connection = JDBCUtil.getInstance().getConnection();

		if (null == connection) {
			LOG.error("The database connction is null, return.");
			return result;
		}

		CallableStatement cs = null;
		int len = params == null ? 0 : params.length;
		int[] index = new int[len];

		try {
			cs = connection.prepareCall(sql);
			int position = 0;

			// 设置入参/出参
			for (int i = 0; i < len; i++) {
				if ("IN".equalsIgnoreCase(params[i][0])) {
					cs.setString(i + 1, params[i][1]);
				} else if ("OUT".equalsIgnoreCase(params[i][0])) {
					cs.registerOutParameter(i + 1,
							Integer.valueOf(params[i][1]));
					index[position] = i + 1;
					position++;
				}
			}
			cs.execute();

			result = new String[position];

			// 处理返回值
			for (int i = 0; i < index.length; i++) {
				if (0 != index[i]) {
					result[i] = String.valueOf(cs.getObject(index[i]));
				}
			}

		} catch (SQLException e) {
			LOG.error("JDBCCore:=>callProcedure : SQLException!", e);
		} catch (Exception e) {
			LOG.error("JDBCCore:=>callProcedure : Exception!", e);
		} finally {
			JDBCUtil.close(connection, null, cs);
		}
		return result;
	}
}