Tomcat 7中JDBC DataSources配置使用

刚刚接触 tomcat ,尝试连接 MySQL 数据库,几乎是照着 tomcat 7 的文档 JDBC DataSources 部分一步步进行,但网页访问时,什么内容也没有。大致过程如下:


1. 本地MySQL数据库已建好,访问TestDB.testdata表格中所有数据。


2. 创建/META-INF/context.xml,内容如下:


<?xml version='1.0' encoding='utf-8'?>

  testdb"

            auth="Container"

            type="javax.sql.DataSource"

            username="yourname"

            password="yourpassword"

            driverClassName="com.mysql.jdbc.Driver"

            url="jdbc:mysql://localhost:3306/TestDB"

            maxActive="8"

            maxIdle="4"/>



3. 创建/WEB-INF/web.xml,内容如下:


   

<?xml  version="1.0" encoding="ISO-8859-1"?>

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

  version="3.0"

  metadata-complete="true">

  

    DB Connection

     jdbc/testdb

    javax.sql.DataSource

    Container

  



4. 创建test.jsp,内容如下:


try {

out.println("Begin.\n");

Context ctx = new InitialContext();

if(ctx == null)

  out.println("InitialContext failed.
");

else

  out.println("InitialContext ok.
");

DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/testdb");

if(ds == null)

  out.println("lookup failed.
");

else

  out.println("lookup ok.
");

Connection conn = ds.getConnection();

out.println("getConnection ok.
");

Statement st = conn.createStatement();

out.println("createStatement ok.
");

ResultSet rs = st.executeQuery("select * from testdata");

while(rs.next()){

out.println(rs.getString(1) + "
");

}

} catch (NamingException e) {

out.println(e.getMessage());

e.printStackTrace();

} catch (SQLException e) {

out.println(e.getMessage());

e.printStackTrace();

}

%>



5. 代码编写完成,进行服务器部署工作,浏览器访问,发现了上述的问题。经过调试,发现在执行Connection conn = ds.getConnection();这行代码时,会报错:

Can't create PoolableConnectionFactory (Communications link failure the last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)



解决方案:

修改context.xml文件

---

url="jdbc:mysql://localhost:3306/TestDB"

+++

url="jdbc:mysql://192.168.0.78:3306/TestDB"

其中192.168.0.78为本机IP地址。



问题分析:

目前估计与mysql的设置相关,bind-address=192.168.0.78

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25432352/viewspace-687891/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/25432352/viewspace-687891/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值