0

我正在尝试servlet/mysql webapp在我的eclipse. 当我尝试连接到databasefrom aservlet时,出现以下错误:

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create 
PoolableConnectionFactory (Access denied for user ''@'localhost' (using password: YES))

下面是我执行的脚本:

小服务程序:

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>
4

3 回答 3

1

如果您从远程客户端访问数据库,请使用 mysql 的GRANT查询授予您访问数据库的权限。

于 2012-10-12T05:27:42.643 回答
1

尝试从任何其他工具/从命令提示符连接到 mysql,并使用您在代码中使用的所有信息连接到相同的。尝试在连接 url 中也包含端口。默认端口为 3306

于 2012-10-10T09:46:19.707 回答
0

url 中似乎缺少端口号:

jdbc:mysql://localhost:<port>/mysql
于 2012-10-10T09:42:36.567 回答