package common; import java.sql.connection; import java.sql.sqlexception; import javax.naming.context; import javax.naming.initialcontext; import javax.naming.namingexception; import javax.sql.datasource; /** * get data source through Jndi * @author Week warrior * Time: December 8, 2008 22:37:09 */public class dbconnection { /** * Get the data source through Jndi to get the connection object * @return connection con */ public static connection getcon () { Connection con = null; try { context ic = new initialcontext (); datasource source = (DataSource) ic.lookup ("Java:comp/env/jdbc/books "); con = source.getconnection (); } catch (namingexception e) {            SYSTEM.OUT.PRINTLN ("Data source not found.) "); e.printstacktrace (); } catch (sqlexception e) { system.out.println ("Get Number of connection objects failed.") "); e.printstacktrace (); } return con;    &NBSP}}
Configuration of Jndi:
1.context.xml file configuration: <resource name= "Jdbc/books" auth= "Container" type= "Javax.sql.DataSource" maxactive= "100" maxidle= "maxwait=" 10000 "username=" sa "password=" 123 "Driverclassname=" Com.microsoft.sqlserver.jdb C.sqlserverdriver "url=" Jdbc:sqlserver://localhost:1433;databasename=books "/>
Configuration of 2.web.xml files: <resource-ref> <res-ref-name> jdbc/books </res-ref-name> <res-type> javax. Sql. DataSource </res-type> <res-auth> Container </res-auth> </resource-ref>
3. Add Database driver files:
Access to the database through the data source, because the data source is maintained by Tomcat, all must copy the JDBC driver to Tomcat's Common/lib directory.
Note: If you use a myeclipce with a self-contained tomcat, you can get it from the Configure
Select Paths-----"Click Add jar/zip-----" to load the corresponding JDBC driver