Business web applications rely on databases. Therefore, you will probably be required to make a connection to your relational database during the development of a web application. Java accesses relational databases through JDBC (Java Database Connectivity). As of JDBC 2, the database is represented to Tomcat as a data source. In this topic I will discuss establishing a JDBC connection to a MySQL data source in Tomcat.
To learn how to establish a JDBC connection in Apache Tomcat, follow these four steps:
testand is used by the "Cool Garden Tools" web application. It contains one table, the
GardenToolstable. The JNDI (Java Naming and Directory Interface) name referenced in the web application is
<Resource name="jdbc/gardentools" auth="Container" type="javax.sql.DataSource" maxTotal="25" maxIdle="5" maxWaitMillis="5000" username="root" password="mypassword" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test"/>
nameattribute value must match the name of the JNDI resource coded in the
lookupmethod of a
Contextin the application code. The
maxWaitMillisare parameters for Database Connection Pool (DBCP) and specify the total connections allowed for this resource, the maximum number of idle, or unused, connections and the maximum wait time in milliseconds before throwing an exception if all connections are in use (a value of -1 indicates that the wait time is infinite), respectively. Note that the
driverClassNameare specific to database vendor. For examples of Oracle and PostgreSQL visit the Tomcat documentation for JNDI
context.xml, Tomcat will detect the updated file, and the resource will be available to your web application.