我正在执行一个查询并将结果放入 JSONObject 以将其返回到 EXTJS 页面。代码有效,但我不确定这是否是最好或最有效的方法。我会发布我的代码,请看看我是否需要改进它以及在哪里。我是新程序员,所以请原谅明显的错误。提前致谢。
public JSONObject execQuery(String invoice, String id){
StringBuffer sb = new StringBuffer();
JSONObject json = new JSONObject();
JSONObject data = new JSONObject();
JSONArray jsArray = new JSONArray();
try{
// get conn
conn = DBConnect.getInstance().dbOracleConnect();
// create query
sb = new StringBuffer("SELECT * FROM table ");
sb.append("WHERE rtrim(invoice) = ? AND ");
sb.append("id = ? ");
ps = conn.prepareStatement(sb.toString());
ps.setString(1, invoice);
ps.setString(2, id);
rs = ps.executeQuery();
while(rs.next()){
json = new JSONObject();
json.put("invoice", rs.getString("invoice"));
json.put("id", rs.getString("id"));
json.put("name", rs.getString("name"));
json.put("gender", rs.getString("gender"));
jsArray.put(json);
// out put will be like [{"invoice":"111", "id":"123", "name":"sam", "gender":"male"}, {...}]
}
data.put("data", jsArray);
// out put will be like {"data":[{"invoice":"111", "id":"123", "name":"sam", "gender":"male"}, {...}]}
}
catch(Exception e){
System.out.println("Error: " + e.toString());
}
finally {
JDBCHelper.close(rs);
JDBCHelper.close(ps);
JDBCHelper.close(conn);
}
return data;
}