/** * Handle all operations with the database through a Basedao * 1. General methods of querying * 2. Common methods of updating * @author Administrator * */ Public class Basedao { Connection objects Connection con= null; PreparedStatement pstmt = null; ResultSet rs = null; C3P0 Data Source Creation private static DataSource ds; Static { ds = new combopooleddatasource (); } /** * Common methods for implementing queries * @param<T> Incoming object types, when calling this method, determine the type * @param sql to query * @param clazz The Incoming object type, the byte code * @param The value of the Paramvalue placeholder (query condition) * @return */ Public <T> list<t> query (String sql,object[] paramvalue,class<t> clazz) { The returned data list<t> list = new arraylist<t> (); Try { 1. Get connection con = ds.getconnection (); 2. Creating stmt Objects pstmt = con.preparestatement (sql); Get the number of placeholders by parameter metadata int count = Pstmt.getparametermetadata (). GetParameterCount (); for (int i=0; i<count; i++) { Set parameter values ..... Pstmt.setobject (i+1, paramvalue[i]); } 3. Get result set rs = Pstmt.executequery (); Get result set meta data ResultSetMetaData RSMD = Rs.getmetadata (); Get the number of columns from the result set meta data int columnCount = Rsmd.getcolumncount (); Traverse result set while (Rs.next ()) { Creating objects T t = clazz.newinstance (); Iterate through each column of the current row for (int i=0; i<columncount; i++) { Column Name "Object Properties" String columnName = Rsmd.getcolumnname (i+1); Column Value "Object property, corresponding value" Object Columnvalue = Rs.getobject (columnName); Copies the specified value to an object of the specified name by beanutils Beanutils.copyproperty (t, ColumnName, Columnvalue); } Add the Encapsulated object (t) to the collection List.add (t); } Catch (Exception e) { throw New RuntimeException (e); finally { this. CloseAll (Con, pstmt, RS); } return list; } /** * * @param SQL-Updated SQL statement * @param The value of the Paramvalues SQL statement parameter */ public int update (String sql,object[] paramvalues) { Try { 1. Get connection con = ds.getconnection (); 2. Creating stmt Objects pstmt = con.preparestatement (sql); Get parameter metadata int count = Pstmt.getparametermetadata (). GetParameterCount (); for (int i=0; i<count; i++) { Set parameter values Pstmt.setobject (i+1, paramvalues[i]); } 3. Execute SQL, returning the number of affected rows return pstmt.executeupdate (); Catch (Exception e) { throw New RuntimeException (e); finally { this. CloseAll (Con, pstmt, null); } } Public void closeall (Connection con, Statement stmt, ResultSet rs) { Try { if (RS!= null) { Rs.close (); rs = null; } if (stmt!= null) { Stmt.close (); stmt = null; } if (Con!= null) { Con.close (); con = null; } Catch (SQLException e) { throw New RuntimeException (e); } } } |