Reprint: C Blog: Lone Male
Use a configuration file to connect to the database, which is the professional term for connection pooling.
The connection pool is responsible for assigning management and freeing the database connection, which allows the program to reuse an existing database connection without repeating the connection.
Frees database connections that have been idle for more than the maximum idle time to avoid database misses due to not releasing the database.
The creation of a connection pool is divided into the following steps:
1. Configure the Context.xml file (tomcat/conf).
1 2 Auth= "Container" 3 4 5 6 username= "database user name" 7 password= "User password " 8 9 maxidle= " ten " />
2: The drive package for the database is placed in the server's Lib folder
3: Get such a connection from MyEclipse, the specific code is as follows
1 PackageCom.upc.dao;2 3 Importjava.sql.Connection;4 ImportJava.sql.ResultSet;5 Importjava.sql.Statement;6 7 ImportJavax.naming.Context;8 ImportJavax.naming.InitialContext;9 ImportJavax.sql.DataSource;Ten One Public classDBConnection { A - protectedConnection Conn; - protectedStatement PS; the protectedResultSet rs; - protectedString SQL; - - PublicConnection Getconn () { + Try { -Context context=NewInitialContext (); +DataSource ds= (DataSource) context.lookup ("java:comp/env/jdbc/database name"); A returnds.getconnection (); at}Catch(Exception e) { - e.printstacktrace (); - return NULL; - } - } - Public voidCloseAll (Connection conn,statement stmt,resultset rs) { in Try { - if(rs!=NULL){ to rs.close (); +rs=NULL; - } the if(stmt!=NULL){ * stmt.close (); $stmt=NULL;Panax Notoginseng } - if(conn!=NULL){ theConn.close ();//The connection pool execution Con.close does not close the TCP connection to the database, but instead returns the connection to the pool + //If you do not close, the connection will remain occupied until the connection in the connection pool is exhausted Aconn=NULL; the } +}Catch(Exception e) { - e.printstacktrace (); $ } $ } -}
You can then create a business class to manipulate the database
configuration file to connect to the database (Mysql)