当前位置: 代码迷 >> Java Web开发 >> servlet连接mySQL报com.mysql.jdbc.exceptions.jdbc4.CommunicationsExcept ...
  详细解决方案

servlet连接mySQL报com.mysql.jdbc.exceptions.jdbc4.CommunicationsExcept ...

热度:851   发布时间:2009-07-16 19:14:53.0
servlet连接mySQL报com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communic
用tomcat作为服务器,lib下有mysql连接的jar包,servlet例子程序里该加载的加载了,该连的也连了,账号密码,数据库都没写错,也加载了tomcat目录下的servlet jar包,web.xml也没搞错。可是在浏览器输入地址后,在tomcat的dos窗口就报com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure这个异常了, 哪位可以帮帮呢?

注明:JDBC或不需要用到tomcat管理数据库的案例都能成功。就需要用到tomcat管理数据库的就不行了,上面那个异常到底什么意思?

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.sql.*;

public class ShowRs extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        response.setContentType("text/html");
        response.setCharacterEncoding("gb2312");
        PrintWriter out = response.getWriter();
        
        out.println("<table border=1>");
        out.println("<tr><td>Content:</td></tr>");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/class?user=root&password=qWERdXzCfsaV");
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from news");
            while(rs.next()){
                out.println("<tr>");
                out.println("<td>" + rs.getString("cont") + "</td>");
                out.println("</tr>");
            }
            out.println("</table>");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null) {
                    rs.close();
                    rs = null;
                }
                if(stmt != null) {
                    stmt.close();
                    stmt= null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

[[it] 本帖最后由 番茄大帝 于 2009-7-18 20:09 编辑 [/it]]
搜索更多相关主题的帖子: fai  exceptions  jdbc  servlet  link  

----------------解决方案--------------------------------------------------------
问题解决了,原来是端口号写错了,千找万找,原来是这个原因,这个例子就是利用servlet尝试连接数据库,有兴趣的可以down下来试一试。
----------------解决方案--------------------------------------------------------
路过,看看
用servlet连接数据库,蛮累的,每次调用servlet就得重新连接一次
不爽.
----------------解决方案--------------------------------------------------------
  相关解决方案