轉自: http://9771104.blog.163.com/blog/static/1944662200991803817362/
?
我的 Tomcat 6.0.20 安裝路徑: D:\Tomcat 6.0
1、 ??? 配置 conf\context.xml 文件
<Resource name="jdbc/mysql_pool" ?auth="Container" ?type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" ?password="sunjie" ?driverClassName="org.gjt.mm.mysql.Driver" url="jdbc:mysql://localhost:3306/testweb" /> 注釋: (總共分 4 欄翻譯) ?? ( 1 )、 JNDI 連接用戶名,作者、類型 ?? ( 2 )、 連接時各大小、各等待時間 ?? ( 3 )、 連接數據庫的用戶名、密碼、以及驅動程序 ?? ( 4 )、 連接數據庫地址我使用的是: testweb 數據庫 在 conf\context.xml 文件中 </Context> 之前,加上以上內容 |
?
?
2、 ??? 配置 conf\web.xml 文件
<resource-ref> ????? <description>DB Connection</description> ????? <res-ref-name>jdbc/mysql_pool</res-ref-name> ????? <res-type>javax.sql.DataSource</res-type> ???? ?<res-auth>Container</res-auth> ?</resource-ref> 注釋: (總共分 3 欄翻譯) ( 1 )、 JNDI 連接用戶名 ? 與上面的 Context.xml 中的 name 匹配 ( 2 )、 JNDI 連接類型 ?? 與上面的 Context.xml 中的 type 匹配 ( 3 )、 JNDI 連接作者 ?? 與上面的 Context.xml 中的 auth 匹配 description 中不做任何解釋,可以自行修改,也可以不修改所內容,使用本人默認的。 在 conf\context.xml 文件中 </web-app> 之前,加上以上內容 |
?
?
3、 ??? 測試是否成功 (保存: test.jsp )
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page imp
<%@ page imp
<%@ page imp
<%! ?????? final String JNDINAME = "java:comp/env/jdbc/mysql_pool" ; %> <% ?????? Connection conn = null ; ?????? try ?????? { ????????????? Context ctx = new InitialContext() ;??? // 初始化查找命名空間 ????????????? DataSource ds = (DataSource)ctx.lookup(JNDINAME) ;?? // 找到 DataSource ????????????? conn = ds.getConnection() ; ?????? } ?????? catch(Exception e) ?????? { ????????????? System.out.println(e) ; ?????? } %> <%=conn%> ??// 打印連接是否成功 注釋: ? ??? 啟動 Tomcat 6.0.20 ,在地址欄輸入: http://localhost:8080/test/test.jsp? 如果出現以下表示成功配置 tomcat 6.0.20 數據源 ? ?????????? jdbc:mysql://localhost:3306/testweb??? 等等什么的, 出現的提示與原先的配置一樣。 |
?
4、 ??? 如果你不確定的話,可以增中如下代碼
注釋: 在 <%=conn%> 后面,增加如下查詢代碼,使用的是 admin 表,其中有 ID , name,pass 三個字段,具體情況根據自己的情況而定。 <table border=1> ?????? <tr> ?????? ?<td> 用戶 ID : </td> ?????? ?<td> 用戶名: </td> ?????? ?<td> 密碼: </td> ?????? </tr> <% ?????? String sql="select * from admin"; ?? PreparedStatement pstat=conn.prepareStatement(sql); ?? ResultSet rs=pstat.executeQuery(); ?? while(rs.next()) ?? { ?? int id=rs.getInt(1); ?? String name=rs.getString(2); ?? String pass=rs.getString(3); %> ?? <tr> ?????? ?<td><%=id%></td> ?????? ?<td><%=name%></td> ?????? ?<td><%=pass%></td> ?? </tr> ?????? <% ?????? } ?????? %> ?????? </table> |
?
錯誤( 1 )、 org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'org.gjt.mm.mysql.Driver'
?
解決辦法: 把連接數據庫的驅動程序,拷貝到 Tomcat 的 lib 文件夾下,就可以。
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
