【问题标题】:How to troubleshoot problems when tomcat servlet connects to mysqltomcat servlet连接mysql时出现问题如何排查
【发布时间】:2016-12-21 06:53:13
【问题描述】:

Tomcat servlet 使用 getConnection() 连接到 mysql。只需从 db test table shop 中获取数据。与 mysql 的连接成功,但浏览器仍不显示来自后端的任何数据。 JavaScript 显示 request.status 为 200,request.readyState 为 2 或 3。我怎样才能找到问题?我什至没有在 tomcat 日志文件中看到任何异常。

public void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws IOException, ServletException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();
        out.println("ok");

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "***");
            Statement statementQuery = connection.createStatement();

            ResultSet set = statementQuery.executeQuery("select * from shop");

            // connection.commit();  Error appears here(should be commented): 
            out.println("<div>");
            while (set.next()) {
                out.println("ok");
                out.println(set.getInt(1) + " ");
                out.println(set.getString(2) + " ");
                out.println(set.getDouble(3));          
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        out.println("</div>");

        out.flush();
        out.close();    
}

public void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws IOException, ServletException {
        doGet(request, response);
}

编辑
connection.commit() 是错误的。评论那一行,它就可以工作了。

【问题讨论】:

    标签: mysql tomcat servlets jdbc


    【解决方案1】:

    把Oracle驱动改成Mysql驱动

    Class.forName("com.mysql.jdbc.Driver");
    

    SQL 语句按顺序执行。将执行顺序改为:

    int ret = statement.executeUpdate("insert into shop values  (53, 'fjd', 43.2)"); 
    ResultSet s1 = statement.executeQuery("select * from shop");
    

    在连接上也执行一次提交

    connection.commit();
    

    并添加finally 以关闭statementconnection

    }finally{
        statement.close();
        connection.close();
    }
    

    【讨论】:

    • 我认为是mysql连接的问题,而不是执行顺序。因为在 sql 语句插入后,表在 db 中没有变化。
    • 您正在使用 oracle 驱动程序。然后使用connection.commit();
    • 您正在重用statement。更新将关闭查询上打开的光标。重新排序,或使用新语句
    • Servlet 仍然无法更新 db 表,因为表没有改变。我将 mysql-connector.jar 放在 tomcat/lib 中。没有其他的。还需要其他工作吗?
    • servlt连接mysql需要web.xml吗?
    猜你喜欢
    • 2014-12-03
    • 1970-01-01
    • 2012-01-13
    • 2014-03-01
    • 1970-01-01
    • 2015-07-02
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多