将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;
}