近日学习jsp时,为连接池的问题所困,经过一番努力,终于成功了,特此为大家献上。
1.Tomcat5.5.12中没有admin模块,需要读者自行下载
2.Tomcat中配置如下 JNDI Name: jdbc/mysql Data Source URL: jdbc:mysql://202.118.133.88/xscj JDBC Driver Class: org.gjt.mm.mysql.Driver User Name: root Password: ******** Max. Active Connections: 4 Max. Idle Connections: 2 Max. Wait for Connection: 500 Validation Query: 注: 1.jdbc/mysql 前纲的jdbc也可以换成其它的, mysql为连池名,可任意起,在下文中注意使用 2.jdbc:mysql://192.168.0.16/xscj xscj为对应的数据库名 也可以换成jdbc:mysql://localhost/xscj 3.JDBC Driver Class : com.mysql.jdbc.Driver jdk中自带 4.User Name:为Mysql中数据库管理员名
3. 下面是最关键的一点
D:Tomcat 5.5confcontext.xml
<!-- The contents of this file will be loaded for each web application --> <Context>
<!-- Default set of monitored resources --> <WatchedResource>WEB-INF/web.xml</WatchedResource> <!-- Uncomment this to disable session persistence across Tomcat restarts --> <!-- <Manager pathname="" /> --> <Resource name="mysql/xscj" type="javax.sql.DataSource" password="kingsoft88" driverClassName="com.mysql.jdbc.Driver" maxIdle="2" maxWait="5000" username="root" url="jdbc:mysql://202.118.133.88:3306/xscj" maxActive="4"/>
</Context>
应相应的字段真加对了就可以了。
4.在Eclipse中编译时加入Tomcat 的DBCP和Pool包就不会有问题了. 测试程序如下:
<html> <head> <title></title> <% out.print("开始测试:"+"<br/>"); DataSource ds = null; Connection con=null; try{ Context initCtx = new InitialContext(); Context ctx = (Context) initCtx.lookup("java:comp/env"); //这里的数据库前文提及的Data Source URL配置里包含的数据库。 ds = (DataSource)ctx.lookup("jdbc/xscj"); con=ds.getConnection(); Statement stmt = con.createStatement(); String strSql = "select * from xs"; //表中的字段读者自行添加 ResultSet rs = stmt.executeQuery(strSql); while(rs.next()){ out.print(rs.getString(1)+"<br/>"); } rs.close(); stmt.close(); con.close(); out.print("我的测试结束"); } catch(Exception ex){ out.print("出现例外,信息是:”+ ex.getMessage()); ex.printStackTrace(); } %> </head> <body> </body> </html>
总结:以上步骤均十分关键,如果有误对应错误如下
1、第一步错误,报错
org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
2、第三步错误,报错
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
3、第四步错误,报错
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket
如果有上述错误,请检查对应步骤是否正确实施
|