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/