/** * The Program class responsible for database connection definition * This class can be responsible for the database connection of all operation threads, and the Get () method can be used to obtain the connection object*/ Public classDatabaseConnection {Private StaticFinal String Dbdriver ="Oracle.jdbc.driver.OracleDriver" ; Private StaticFinal String Dburl ="Jdbc:oracle:thin: @localhost: 1521:orcl" ; Private StaticFinal String USER ="Scott" ; Private StaticFinal String PASSWORD ="Tiger" ; Private StaticThreadlocal<connection> ThreadLocal =NewThreadlocal<connection>() ; /** * Responsible for the external department. Gets the database connection object, which is obtained through threadlocal, if the current thread does not have a saved connection object, creates a new connection * @return Connection object*/ Public StaticConnection getconnection () {Connection conn= ThreadLocal.Get() ;//First Judge If there is a connection object in the threadlocal. if(conn = =NULL) {//first time use, no connection, no connection should create a connectionconn = Connectiondatabase ();//Get Connection ObjectThreadLocal.Set(conn);//Save the Connection object you just created in threadlocal } returnconn;//return Connection Object } /** * The database is closed for processing. */ Public Static voidClose () {Connection conn= ThreadLocal.Get() ; if(Conn! =NULL) {//now there's a connection object. Try{conn.close (); } Catch(SQLException e) {e.printstacktrace (); } threadlocal.remove (); //removes the specified connection from the current thread } } /** * Responsible for creating a database Connection object * Instantiated object @return database connection*/ Private StaticConnection Connectiondatabase () {//This method can only be called by this classConnection conn =NULL ; Try{//Once the connection error occurs, the entire program is not executedClass.forName (Dbdriver); Conn=drivermanager.getconnection (Dburl, USER, PASSWORD); } Catch(Exception e) {e.printstacktrace (); } returnconn;//Get database Connection object }}
Get database connection objects (including threads)