Reusable SQL Operations Classes
1 PublicResultSet doquery (String sql,object[] params) {2ResultSet rs =NULL;3conn = This. getconnection ();4 Try{5PreparedStatement pstmt =conn.preparestatement (SQL);6 for(intI =0;i<params.length;i++){7Pstmt.setobject (i+1, Params[i]);8 }9rs =pstmt.executequery ();Ten}Catch(Exception e) { One e.printstacktrace (); A } - returnrs; -}
1 Public intdoupdate (String sql,object[] params) {2 intres = 0;3conn = This. getconnection ();4 Try{5PreparedStatement pstmt =conn.preparestatement (SQL);6 for(inti=0;i<params.length;i++){7Pstmt.setobject (i+1, Params[i]);8 }9res =pstmt.executeupdate ();Ten}Catch(Exception e) { One e.printstacktrace (); A } - returnRes; -}
1 PublicList<object>doquerylist (String sql,object []params) {2list<object> list =NewArraylist<object>();3ResultSet rs = This. Doquery (sql, params);4 Try{5ResultSetMetaData RSMD =Rs.getmetadata ();6 intColumnlength =Rsmd.getcolumncount ();7 while(Rs.next ()) {8map<string,object> map =NewHashmap<string,object>();9 for(inti = 1;i<=columnlength;i++){Ten Map.put (Rsmd.getcolumnlabel (i), rs.getobject (i)); One } A list.add (map); - } -}Catch(Exception e) { the e.printstacktrace (); - } - returnlist; - }
The JSP key code that queries all information is as follows
1<%2Dbcon DBC =NewDbcon ();3String sql = "SELECT * FROM Schema.admin";4List List = Dbc.doquerylist (sql,Newobject[]{});5 6%>7<table border= "1" >8<% for(intI =0;i<list.size (); i++){9map<string,object> map = (map<string,object>) List.get (i);Ten%> One<tr> A<td><%=map.get ("id")%></td> -<td><%=map.get ("username")%></td> -<td><%=map.get ("password")%></td> the<td><a href= "do_delete.jsp?id=<%=map.get (" id ")%>" > Delete </a></td> -<td><a href= "do_edit.jsp?id=<%=map.get (" id ")%>" > Edit </a></td> -</tr> -<%} + dbc.close (); -%> +</table> A<a href= "addadmin.jsp" > Add Users </a>
Update, delete the same operation, no longer listed.
Prevent SQL injection attacks with pre-compilation