可以从Eclipse ping MySQL但无法在Tomcat中使用JSP进行连接

时间:2015-03-28 09:15:34

标签: mysql eclipse jsp tomcat

我可以从Eclipse DataSource Explorer连接到MySQL数据库(ping成功),但是从Eclipse运行Tomcat Server中的代码不会连接到DB。我收到“无法连接......”的消息。

<%@page import="java.sql.*"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%
try {

Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:8889/LenderDetails", "root", "root");

out.println("connection ="+connection.toString());

if(!connection.isClosed())
%>
<% 
out.println("Successfully connected to " + "MySQL server using TCP/IP...");
connection.close();
}
catch(Exception ex){
%>
<%
out.println("Unable to connect to database.");
}
%>

JSP代码中的URL与DataSourceExplorer中的URL完全相同。

Eclipse Luna(4.4.2),Tomcat V7.0,mysql-connenctor-java-5.1.24-bin.jar,Java SE 7.

为什么我无法从JSP连接或我可以找到更多详细信息(Tomcat日志)的任何想法?

2 个答案:

答案 0 :(得分:0)

你有问题。 连接连接= DriverManager.getConnection("com.mysql.jdbc:mysql://localhost:8889/LenderDetails", "root", "root“);

只需替换为。

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:8889/LenderDetails", "root", "root");

您的代码将如下所示。

%@page import="java.sql.*"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%
try {

Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:8889/LenderDetails", "root", "root");

out.println("connection ="+connection.toString());

if(!connection.isClosed())
%>
<% 
out.println("Successfully connected to " + "MySQL server using TCP/IP...");
connection.close();
}
catch(Exception ex){
%>
<%
out.println("Unable to connect to database.");
}
%>

答案 1 :(得分:0)

通过将mysql-connector-java-5.1.24-bin.jar包含到项目的部署程序集中来解决这个问题。