Java database operation simple processing, the following code can be, package the additions and deletions to check and get connections, close the connection.
The code is as follows:
Packagecom.test;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;/*** Operation Database Tool class * **/ Public classDbutil {/*** Connection Data * *@returnConn*/ Public StaticConnection getconnection (String driver,string url,string username,string password) {Connection conn=NULL; Try{class.forname (driver); Conn=drivermanager.getconnection (URL, username, password); } Catch(Exception e) {e.printstacktrace (); } returnConn; } /*** Close Connection Object * *@paramConn * Connection Object *@parampstmt * Precompiled objects *@paramRS * result set*/ Public Static voidCloseAll (Connection conn, PreparedStatement pstmt, ResultSet rs) {Try { if(rs! =NULL) {rs.close (); } if(Pstmt! =NULL) {pstmt.close (); } if(Conn! =NULL) {conn.close (); } } Catch(Exception e) {e.printstacktrace (); } } /*** Delete and change operation * *@paramSQL * SQL command *@paramparam * Parameters *@return */ Public Static intexecutupdate (Connection conn,string sql, object[] param) {intresult = 0; PreparedStatement pstmt=NULL; Try{pstmt=conn.preparestatement (SQL); if(param! =NULL) { for(inti = 0; i < param.length; i++) {Pstmt.setobject (i+ 1, Param[i]); }} result=pstmt.executeupdate (); } Catch(Exception e) {e.printstacktrace (); } finally{closeall (conn, pstmt,NULL); } returnresult; } /*** Enquiry * *@returnint * @date 2015-7-25 a.m. 11:10:06*/ Public StaticResultSet executquery (Connection conn,string sql, string[] param) {preparedstatement pstmt=NULL; ResultSet result=NULL; Try{pstmt=conn.preparestatement (SQL); if(param! =NULL) { for(inti = 0; i < param.length; i++) {pstmt.setstring (i+ 1, Param[i]); }} result=Pstmt.executequery (); } Catch(Exception e) {e.printstacktrace (); } returnresult; }}
Java Tools Class--Database Operations encapsulation class