我正在尝试在我的servlet/mysql webapp
中使用tomcat服务器运行一个简单的eclipse
。
当我尝试从database
连接到servlet
时,出现以下错误:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create
PoolableConnectionFactory (Access denied for user ''@'localhost' (using password: YES))
下面的是我执行的脚本:
servlet:
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class EmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Resource(name = "jdbc/testDB")
DataSource ds;
public EmployeeServlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
String query = "select * from Employee";
ResultSet rs = stmt.executeQuery(query);
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<center><h1>Employee Details</h1></center>");
out.print("<html><body>");
out.print("<table border=\"1\" cellspacing=10 cellpadding=5>");
out.print("<tr><th>Employee ID</th>");
out.print("<th>Employee Name</th>");
out.print("<th>Salary</th>");
out.print("<th>Department</th></tr>");
while (rs.next()) {
out.print("<tr>");
out.print("<td>" + rs.getInt("emp_id") + "</td>");
out.print("<td>" + rs.getString("emp_name") + "</td>");
out.print("<td>" + rs.getDouble("salary") + "</td>");
out.print("<td>" + rs.getString("dept_name") + "</td>");
out.print("</tr>");
}
out.print("</table></body></html>");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
context.xml文件的内容:
<?xml version="1.0" encoding="UTF-8"?>
<Context crossContext="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/testDB" auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/mysql">
</Context>
答案 0 :(得分:1)
尝试从任何其他工具/从命令提示符连接到mysql,并将您在代码中使用的所有信息连接到同一个。尝试在连接URL中包含端口。默认端口是3306
答案 1 :(得分:1)
如果从远程客户端访问数据库,请使用mysql的GRANT
查询授予您访问数据库的权限。
答案 2 :(得分:0)
似乎网址中缺少端口号:
jdbc:mysql://localhost:<port>/mysql