日期:2014-05-16 浏览次数:20497 次
/** * 执行存储过程(和参数顺序无关) * @param procName 存储过程名称 * @param procParam 参数(key需大写) * @return */ public static Map<String, Object> executeProcedure(String procName, Map<String, Object> procParam) { Connection conn = null; CallableStatement cs = null; PreparedStatement ps = null; ResultSet rs=null; String sqlCall = ""; Map<String, List<Integer>> outParaIdxMap = new LinkedHashMap<String, List<Integer>>(); try { conn = getConnection(dbResourceName); DatabaseMetaData dbmd = conn.getMetaData(); sqlCall = "{call " + procName + "("; String pckgName = procName.lastIndexOf(".") > 0 ? procName .substring(0, procName.lastIndexOf(".")).toUpperCase() : null;//有包体时 String proc = procName.substring(procName.lastIndexOf(".") + 1, procName.length()).toUpperCase(); rs = dbmd.getProcedureColumns(pckgName,"" , proc, null); int i = 1; while (rs.next()) {// 拼装参数 String columnName = rs.getString("COLUMN_NAME"); Short columnType = rs.getShort("COLUMN_TYPE"); int dataType = rs.getInt("DATA_TYPE"); List<Integer> outParaList=new ArrayList<Integer>(); if (DatabaseMetaData.procedureColumnIn==columnType){ sqlCall += columnName + "=>'" + procParam.get(columnName) + "',"; } else if (DatabaseMetaData.procedureColumnOut==columnType) {// 输出参数 sqlCall += columnName + "=>?,"; outParaList.add(i); outParaList.add(dataType); outParaIdxMap.put(columnName,outParaList); i++; } } sqlCall = sqlCall.substring(0, sqlCall.lastIndexOf(",")) + ")}";//去除参数最后一个逗号以及后面的部分 cs = conn.prepareCall(sqlCall); for (String key : outParaIdxMap.keySet()) { int idx=outParaIdxMap.get(key).get(0);//顺序 int dataType=outParaIdxMap.get(key).get(1);//dataType cs.registerOutParameter(idx, dataType); } cs.execute(); for (String key : outParaIdxMap.keySet()) {//组装输出参数值(保留输入参数值) int idx=outParaIdxMap.get(key).get(0);//顺序 procParam.put(key, cs.getObject(idx)); } conn.commit(); } catch (Exception e) { System.err.println("SQLException proc=[" + sqlCall + "] "); try { if (conn != null) conn.rollback(); } catch (SQLException sqlex) { sqlex.printStackTrace(); } e.printStackTrace(); } finally { closeRsPsConn(rs, ps, conn); closeCsPsConn(cs, ps, conn); } return procParam; } /** * 把key装换为大写便于后台处理 * @param map * @return */ public static Map<String, Object> convertUpperCaseMap(Map<String, ?> map) { Map<String, Object> returnMap=new LinkedHashMap<String, Object>(); for (String key : map.keySet()) { returnMap.put(key.toUpperCase(), map.get(key)); } return returnMap; }