Two methods:
I. Tomcat server configuration:
1. Set <Resource name = "jdbc/TestDB" auth = "Container" type = "javax. SQL. DataSource"
MaxActive = "100" maxIdle = "30" maxWait = "10000"
Username = "root" password = "sa" driverClassName = "com. mysql. jdbc. Driver"
Url = "jdbc: mysql: // localhost: 3306/employee_manager? AutoReconnect = true "/>
Paste it to <context> </Context> In the Tomcat 6.0/conf Context. xml file.
2. Set <resource-ref>
<Description> DB Connection </description>
<Res-ref-name> jdbc/TestDB </res-ref-name>
<Res-type> javax. SQL. DataSource </res-type>
<Res-auth> Container </res-auth>
</Resource-ref>
Paste the file to the web. xml file <web-app> </web-app>
3. Place the database driver file in Tomcat 6.0/lib.
4. Application in the program:
Public static Connection getConnection (){
DataSource ds;
InitialContext cxt;
Try {
Cxt = new InitialContext ();
Ds = (DataSource) cxt. lookup ("java:/comp/env/jdbc/TestDB ");
Con = ds. getConnection ();
} Catch (Exception e ){
E. printStackTrace ();
}
SqlServer2005 is the same as the preceding steps:
Url = "jdbc: microsoft: sqlserver: // 127.0.0.1: 1433; DatabaseName = employee_manager"
? AutoReconnect = true should be deleted!
Oracle:
<Context>
<Resource
Name = "jdbc/ums"
Type = "javax. SQL. DataSource"
Username = "neu"
Password = "oracle"
Url = "jdbc: oracle: thin: 127.0.0.1: 1521: ORACLE"
DriverClassName = "oracle. jdbc. driver. OracleDriver"
MaxIdle = "2"
MaxWait = "5000"
MaxActive = "4"/>
<WatchedResource> WEB-INF/web. xml </WatchedResource>
</Context>
Skip Step 1
Applicable to All tomcat Projects
2. Configure in the project:
1. Create a context. xml file in the WebRoot/META-INF with the following content:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Context>
<Resource name = "jdbc/ORACLE"
Auth = "Container"
Type = "javax. SQL. DataSource"
DriverClassName = "oracle. jdbc. driver. OracleDriver"
Url = "jdbc: oracle: thin: @ 127.0.0.1: 1521: orcl"
Username = "scott"
Password = "tiger"
MaxActive = "100"
MaxIdle = "30"
MaxWait = "10000" type = "codeph" text = "/codeph"/>
</Context>
2. Use the following code:
Try {
InitialContext initContext = new InitialContext ();
Context context = (Context) initContext. lookup ("java: comp/env ");
DataSource ds = (DataSource) context. lookup ("jdbc/ORACLE ");
Conn = ds. getConnection ();
System. out. println ("connect to the database through the connection pool. ");
} Catch (Exception e ){
Throw new ServletException (e );