您的位置:首页 > 数据库

如何将sql转化为json数据

2015-12-03 11:14 218 查看

//将sql代码转化为json格式的数据
public String getJsonStr(String sql,String jsonName){
String jsonStr = "";
String tjson = "";
Connection con = null;
ResultSet rs = null;
PreparedStatement pst = null;
con = sh.getConnection();
HashMap<String,Object> hm = sh.select(con, pst, rs, sql, null);
rs = (ResultSet)hm.get("ResultSet");
int colNum;
try {
colNum = rs.getMetaData().getColumnCount();
String colName[] = new String[colNum];
for(int i= 0;i<colNum;i++)
colName[i] = rs.getMetaData().getColumnName(i+1);
while(rs.next()){
jsonStr += "{";
String temp = "";
for(int i= 0;i<colNum;i++){
temp += "\"";
temp += colName[i];
temp += "\":\"";
temp += rs.getString(i+1);
temp += "\",";
}
jsonStr += temp.substring(0, temp.length()-1);
jsonStr += "},";
}
tjson += "{\""+jsonName + "\":[";
if(jsonStr!="")
tjson += jsonStr.substring(0, jsonStr.length()-1);
tjson += "]}";
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pst = (PreparedStatement)hm.get("PreparedStatement");
sh.closeAll(rs, pst, con);
return tjson;
}

转载于:https://my.oschina.net/u/1987870/blog/538749

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: