Oracle存儲過程的調用以及返回結果集的提取


DEMO例子

 
        
/****
* 查詢用戶所有持有的產品(DEMO)
* @param session
* @param clientNo
* @param productCode
* @return
* @throws MallException
*/
public Map<String, Object> queryUserProduct(Session session, int clientNo, String productCode) throws MallException {

Connection connection = null;
CallableStatement callableStatement = null;
ResultSet resultSet = null;
String errorMsg = "";
int errorcode = -1;
List<Map> result = null;
try {
connection = session.connection();//按需替換成自己的connection
connection.setAutoCommit(false);
String callProcSql = "{ call QUERY_USER_PRODUCT (?,?,?,?) }";

callableStatement = connection.prepareCall(callProcSql);
//存儲過程入參
callableStatement.setInt(1, clientNo);//客戶號
callableStatement.setString(2, productCode);//產品代碼
callableStatement.registerOutParameter(4, -10); //輸出的是結果集
callableStatement.registerOutParameter(5, -10);
callableStatement.execute();
resultSet = (ResultSet) callableStatement.getObject(4);
try {
if (resultSet != null) {
result = extractData(resultSet);//結果集抽取
if (result != null && result.size() > 0) {
try {
errorcode = Integer.parseInt(result.get(0).get("error_code") + "");
} catch (Exception e) {
e.printStackTrace();
}
errorMsg = (String) result.get(0).get("error_msg");
}
}
} finally {
if (resultSet != null){
resultSet.close();
}
}

if (connection != null) {
connection.commit();
}

} catch (Exception ex) {
ex.printStackTrace();
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e) {
e.printStackTrace();
}
errorMsg = ex.getMessage(); //返回的錯誤消息按需定義
} finally {
try {
if (callableStatement != null) {
callableStatement.close();
callableStatement = null;
}
if (connection != null && !connection.isClosed()) {
connection.close();
}
connection = null;
} catch (Exception e) {
e.printStackTrace();
}
}
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("error_msg", errorMsg);
resultMap.put("error_code", errorcode);
return resultMap;
}

/**
* 返回的結果集提取
* 轉為List<Map>
* @param resultSet
* @return
* @throws SQLException
*/
private List<Map> extractData(ResultSet resultSet) throws SQLException {
if (resultSet == null) {
return null;
}
ResultSetMetaData metaData = resultSet.getMetaData();
List<Map> result = new ArrayList<Map>();
while (resultSet.next()) {
Map map = new LinkedHashMap();
for (int i = 0; i < metaData.getColumnCount(); i++) {
Object o = resultSet.getObject(metaData.getColumnName(i + 1));
String key = ((String) metaData.getColumnName(i + 1)).toLowerCase();
map.put(key, resultSet.getString(metaData.getColumnName(i + 1)));
}
result.add(map);
}
return result;
}
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM