將oracle數據庫中一個表中的一些字段的值封裝成Json數組


使用一種不適用API的方式將oracle數據庫中一個表中的一些字段的值封裝成Json數組,具體java代碼如下:

/**
*
* @param jsonSql   需要查詢的數據的sql語句
* @param api_tablename  被封裝的表數據的表名(用於查詢字段的類型)
* @param colNmaes  需要被封裝進Json數組中的字段的名稱
* @param listName  JSon數組的名稱
* @param api_rownum  需要查詢的表的行數
* @return
* @throws Exception
*/

public String JavaCreateJson(String jsonSql, String api_tablename,

String colNmaes, String listName, String api_rownum)
throws Exception {
String builder = "";
ResultSet rs = null;
Statement stmt = null;
if (!(api_rownum == null || api_rownum.length() <= 0)) {
jsonSql = jsonSql + " and rownum < " + api_rownum;
}

try {
stmt = con.createStatement();
rs = stmt.executeQuery(jsonSql);

String[] column = colNmaes.split(",");// 拆分字符為"," ,然后把結果交給數組
builder = "{\"" + listName + "\":[";
// 開始構建Json結構
while (rs.next()) {
builder += "{";
for (int i = 0; i < column.length; ++i) {
builder = builder + "\"" + column[i] + "\":";
String coldata = rs.getString(column[i]);
String sql_table = "select t.data_type from user_tab_columns t "
+ " where t.table_name = upper('"
+ api_tablename
+ "') "
+ " and t.column_name = upper('"
+ column[i] + "')" + " order by t.column_id";

DBTableModel model_col = null;
try {
model_col = new SelectHelper(sql_table).executeSelect(
con, 0, 1);
} catch (Exception e) {
// logInfo("error","系統","獲取設置記錄異常!錯誤信息:\n"+e.getMessage(),null);
e.printStackTrace();
}

String ColumnType = model_col.getItemValue(0, "data_type");

if (ColumnType.equalsIgnoreCase("NUMBER")) {
if (!(coldata == null || coldata.length() <= 0)) {
builder = builder + coldata;
}
} else {
if (coldata == null || coldata.length() <= 0) {
builder = builder + "\"\"";
} else {
builder = builder + "\"" + coldata + "\"";
}
}
if (i < column.length - 1) {
builder = builder + ",";
}
}

builder = builder + "},";
}
if (builder.equals("{\"" + listName + "\":[")) {
builder = null;
}
if (!(builder == null || builder.length() <= 0)) {
builder = builder.substring(0, builder.length() - 1);
builder = builder + "]}";
}
// System.out.println(builder.toString());
rs.close();
stmt.close();
} catch (Exception e) {
// logInfo("error","系統","-----創建Json錯誤-----錯誤信息:"+e.getMessage(),null);
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
} catch (Exception e) {
// logInfo("error","系統","-----創建Json錯誤-----錯誤信息:"+e.getMessage(),null);
e.printStackTrace();
}
}

return builder;
}


免責聲明!

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



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