1.properties configuration file
driver=com.mysql.jdbc.driver#urlurl=jdbc:mysql://Localhost:3306/pabitel# Useruser=Root#passwordpassword=493656696
2. Build a class to get the connection
1 Public classDBHelper {2 PrivateDBHelper () {}3 Private StaticString URL;4 Private StaticString driver;5 Private StaticString user;6 Private StaticString pwd;7 Private StaticThreadlocal<connection> tl=NewThreadlocal<connection>();8 Static{9 Try {TenProperties prop=NewProperties (); OneInputStream Is=dbhelper.class. getClassLoader (). getResourceAsStream ("Properties.properties"); A Prop.load (IS); -Driver=prop.getproperty ("Driver"); -User=prop.getproperty ("User"); thePwd=prop.getproperty ("Password"); -Url=prop.getproperty ("url"); - Class.forName (driver); -}Catch(Exception e) { + e.printstacktrace (); - Throw NewRuntimeException (e); + } A } at Public StaticConnection getconnection ()throwssqlexception{ -Connection conn=drivermanager.getconnection (url,user,pwd); - Tl.set (conn); - returnConn; - } - Public Static voidCloseConnection () { inConnection conn=tl.get (); - if(conn!=NULL){ to Try { + conn.close (); -}Catch(SQLException e) { the //TODO auto-generated Catch block * e.printstacktrace (); $ }Panax Notoginseng Tl.remove (); - } the } +}
Use of 3.threadlocal
It is similar to map,key-value combination, key is thread, value is connection
4. Use of the thread pool
Define the thread pool private static Basicdatasource ds;
Subsequent setting of the following parameters in the static block
1ds=NewBasicdatasource ();3Ds.setdriverclassname (Prop.getproperty ("Driver"));4Ds.seturl (prop.getproperty ("url"));5Ds.setusername (Prop.getproperty ("User"));6Ds.setpassword (Prop.getproperty ("PSW"));7Ds.setinitialsize (Integer.parseint (Prop.getproperty ("Initsize")));8Ds.setmaxactive (Integer.parseint (Prop.getproperty ("Maxactive")));9Ds.setmaxwait (Integer.parseint (Prop.getproperty ("maxwait")));TenDs.setminidle (Integer.parseint (Prop.getproperty ("Minidle"))); OneDs.setmaxidle (Integer.parseint (Prop.getproperty ("Maxidle"));
You can use the thread pool to get the connection.
JDBC Connection MySQL