在tomcat的安裝的目錄下找到context.xml,在context節點加入<Resource/>節點java
<Context> <!-- Default set of monitored resources --> <WatchedResource>WEB-INF/web.xml</WatchedResource> <!-- Uncomment this to disable session persistence across Tomcat restarts --> <!-- <Manager pathname="" /> --> <!-- Uncomment this to enable Comet connection tacking (provides events on session expiration as well as webapp lifecycle) --> <!-- <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> --> <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="10" maxWait="5000" username="json" password="123456" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://192.168.1.101:3306/study_web" /> </Context>
把鏈接數據庫的jar包放入tomecat人安裝目錄下lib目錄中 mysql
在web項目中找到web.xml,加入以下配置:web
<resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/mysql</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
而後使用以下代碼獲取DataSource:sql
package dal; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class TestDB { public void getConnection() throws SQLException { try { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/mysql"); if (ds != null) { System.out.println("已經獲取到dataSource"); Connection conn = null; conn = ds.getConnection(); Statement stmt; stmt = conn.createStatement(); String sql = "select * from user"; ResultSet rs = stmt.executeQuery(sql); rs.next(); System.out.println(rs.getInt(1)); System.out.println(rs.getString(2)); conn.close(); } } catch (NamingException e) { e.printStackTrace(); } } }