配置Tomcat連接池
首先在Tomcat7下面的conf/context.xml中的<context>標簽中添加屬性:
<Resource name="jdbc/imooc" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="123456" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test" />
然后在項目中的web.xml中的<web-app>添加如下配置:
<description>MySQL Test App</description> <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/imooc</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
值得注意的是Tomcat中的name必須和web.xml中的<res-ref-name>jdbc/imooc</res-ref-name>
保持一致。
Jsp頁面調用
<%@ page contentType="text/html; charset=UTF-8" %> <%@ page import = "javax.naming.*,java.sql.*,javax.sql.*" %> <% String result=""; String test=""; Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:/comp/env"); DataSource ds = (DataSource)envContext.lookup("jdbc/imooc"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from imooc_goddess"); while(rs.next()){ result +="\n 第一字段內容:" + rs.getString(2)+"<br>"; } conn.close(); %> <%=result %>
上面的相對應的代碼也可以
Context initContext = new InitialContext(); DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/imooc");
但是推薦使用第一種方式。。
本文由用戶 cwf8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!