1. Configure the context. xml file under the conf directory in Tomcat
<Resource Name = "JDBC/Ds"
Auth = "Container"
Type = "javax. SQL. datasource"
Maxactive = "100"
Maxidle = "30"
Maxwait = "10000"
Username = "sa"
Password = "123456a"
Driverclassname = "com. Microsoft. sqlserver. JDBC. sqlserverdriver"
Url = "JDBC: sqlserver: // localhost: 1433; databasename = qqdb ;"
/>
2. Obtain the data source.
Javax. Naming. Context CTX = NULL;
Datasource DS = NULL;
Try {
CTX = new javax. Naming. initialcontext ();
DS = (datasource) CTX. Lookup ("Java: COMP/ENV/jdbc/Ds ");
System. Out. println ("Data source:" + DS );
} Catch (namingexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
3. Note: Since the JNDI data source is driven by a Web Container, copy the database driver to the lib directory in Tomcat,
It can only be accessed on the web page, and cannot be tested locally (to be improved)
Test the configuration of the database connection pool (action) in JNDI)
Package com. Wang. owbhome. Web. Action;
Import java. SQL. connection;
Import java. SQL. sqlexception;
Import javax. Naming. namingexception;
Import javax. servlet. servletcontext;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import javax. servlet. jsp. jstl. SQL. result;
Import javax. SQL. datasource;
Import org. Apache. Struts. action. Action;
Import org. Apache. Struts. Action. actionform;
Import org. Apache. Struts. Action. actionforward;
Import org. Apache. Struts. Action. actionmapping;
Import com. Wang. owbhome. Business. util. dB;
Public class testdatasourceaction extends action {
Public actionforward execute (actionmapping mapping, actionform form,
Httpservletrequest request, httpservletresponse response)
Throws exception {
// Code of the todo Test Data Connection Pool
Javax. Naming. Context CTX = NULL;
Datasource DS = NULL;
Try {
CTX = new javax. Naming. initialcontext ();
DS = (datasource) CTX. Lookup ("Java: COMP/ENV/jdbc/Ds ");
System. Out. println ("Data source:" + DS );
} Catch (namingexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Connection conn = Ds. getconnection ();
DB = new dB ();
DB. setconnection (conn );
String sql1 = "select * From qquser ";
DB. setsqlvalues (sql1 );
Try {
Result rs = db.exe cutequery ();
If (rs = NULL | Rs. getrowcount () = 0 ){
System. Out. println ("no result ");
} Else {
System. Out. println ("Total" + Rs. getrowcount () + "results! ");
}
DB. closeconn ();
} Catch (sqlexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
System. Out. println ("Ni ");
Return Mapping. findforward ("success ");
}
}