Get the result set from the database
Public String list () throws Exception {Connection con=NULL; Pagebean Pagebean=NewPagebean (Integer.parseint (page), Integer. parseint (rows)); Try{con=Dbutil.getcon (); Jsonobject result=NewJsonobject (); Jsonarray Jsonarray= Jsonutil.formatrstojsonarray (Userdao.userlist (Con, pagebean));//the data obtained are as follows: //Zhang 312,233 12345672233 [email protected] //12345672233 turns out to be a tightly knit string, and then converts the result set into a JSON array, formatted intTotal = Userdao.usercount (con);//Get TotalResult.put ("Rows", Jsonarray); Result.put ("Total", total);//Show Total PageResponseutil.write (Servletactioncontext.getresponse (), result); } Catch(Exception e) {e.printstacktrace (); } finally { Try{Dbutil.closecon (con); } Catch(Exception e) {e.printstacktrace (); } } return NULL; }
Convert the result set to a JSON format:
Package Com.java1234.util;import Net.sf.json.jsonarray;import net.sf.json.jsonobject;import Com.mysql.jdbc.resultsetmetadata;public class Jsonutil {/** * convert resultset collection to jsonarray array * * @param RS * @return * @throws Exception*/Public static Jsonarray Formatrstojsonarray (ResultSet rs) throws Exception {ResultSetMetaData MD= Rs.getmetadata ();//Get Table Structure intnum = Md.getcolumncount ();//get the total number of rowsJsonarray array =NewJsonarray ();//JSON array, looking for value according to subscript; [{name1:wp},{name2:{name3: ' ww '}}]name is the key value, WP is the value //Jsonarray Array=jsonarray.fromobject (string); Convert string to Jsonarray format while(Rs.next ()) {//if there are values in the result setJsonobject mapofcolvalues =NewJsonobject ();//creating a JSON object is a {NAME:WP} for(inti = 1; I <= num; i++) {mapofcolvalues.put (Md.getcolumnname (i), rs.getobject (i));//Add a key-value pair, for example {NAME:WP} to find Wp by nameSystem.out.println (mapofcolvalues.tostring ()); } array.add (Mapofcolvalues); } returnArray; }}
Convert from database to data to JSON format (iii)