/*** Created by Clear on 2018/8/11. * Here provide the kind of connections from MySQL Database,and close the resources o f the MySQL * there is * Load driver * Use properties file * With XML file * use Tomcat * and ... so on * * **/ Public classMysqlutil {/*** Link Database*/ /*** Method One: * Load driver*/ Public StaticConnection getconnectionone (String database,string username,string password) {Try{class.forname ("Com.mysql.jdbc.Driver"); Connection Connection= Drivermanager.getconnection ("jdbc:mysql://localhost:3306/" +database,username, password); returnconnection; }Catch(Exception e) {e.printstacktrace (); } return NULL; } /*** Method Two: * Use properties File *::::: File is difficult to locate in Web programming*/ Public StaticConnection Getconnectiontwo () {/*** Document Creation*/Properties Pro=NewProperties (); InputStream in= Mysqlutil.class. getClassLoader (). getResourceAsStream ("Mysqllog.properties"); Try{pro.load (in); Class.forName (Pro.getproperty ("Driver")); String username= Pro.getproperty ("User"); String Password= Pro.getproperty ("Password"); String Database= Pro.getproperty ("Database"); String URL= Pro.getproperty ("url"); Connection Connection= Drivermanager.getconnection (url+Database,username,password); returnconnection; } Catch(Exception e) {e.printstacktrace (); } return NULL; } //Connection, Statement, ResultSet the closing of these resources is in order. Public Static voidClose (object...objects)throwsmysqlcloseexception {Map<String,Object> map =NewHashMap (); for(Object o:objects) {if(OinstanceofResultSet) {Map.put ("ResultSet", O); }Else if(OinstanceofConnection) {Map.put ("Connection", O); }Else if(OinstanceofStatement) {Map.put ("Statement", O); }Else if(OinstanceofPreparedStatement) {Map.put ("PreparedStatement", O); }Else{ Throw NewMysqlcloseexception ("Close exception, cannot handle"); }} Object obj= Map.get ("ResultSet"); if(obj!=NULL) {ResultSet R=(ResultSet) obj; Try{r.close (); Map.Remove ("ResultSet"); } Catch(SQLException e) {e.printstacktrace (); }} obj= Map.get ("PreparedStatement"); if(obj!=NULL) {PreparedStatement P=(preparedstatement) obj; Try{p.close (); Map.Remove ("PreparedStatement"); } Catch(SQLException e) {e.printstacktrace (); }} obj= Map.get ("Statement"); if(obj!=NULL) {Statement s=(Statement) obj; Try{s.close (); Map.Remove ("Statement"); } Catch(SQLException e) {e.printstacktrace (); }} obj= Map.get ("Connection"); if(obj!=NULL) {Connection C=(Connection) obj; Try{c.close (); Map.Remove ("Connection"); }Catch(SQLException e) {e.printstacktrace (); } } }}
Java MySQL database link and resource shutdown