【问题标题】:Database connection not working through Servlet [duplicate]数据库连接无法通过 Servlet [重复]
【发布时间】:2016-02-18 17:34:47
【问题描述】:

我只是想在我的 servlet 上建立连接并输出查询。

当我使用相同的代码在单独的项目上运行但作为 Java 应用程序而不是作为 servlet 运行时,我得到了这个工作。司机也在正确的地方。

下面是我在 servlet 上的代码:

package myproject;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class jdbc
 */
@WebServlet("/jdbc")
public class jdbc extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public jdbc() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    public static Connection con;

    protected static void main(String[] argv) {
        try {
            connectionQuery();

            PreparedStatement statement = con.prepareStatement("SELECT * from Music_Categories");/*write query inside of prepared statement*/
            ResultSet result = statement.executeQuery();
            System.out.println("DataBase table accessed");

            while (result.next()) {
                String retrievedid = result.getString("name");
                System.out.println(retrievedid);
            }

            con.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage().toString());
        }
    }

    protected static void connectionQuery() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/newschemam?useSSL=false", "root", "root");
            System.out.println("Remote DB connection established");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("Remote server could not be connected");
        } catch (NullPointerException e) {
            e.printStackTrace();
            System.out.println("Remote server could not be connected");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("Remote db connection establishment error");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("False query");
        }
    }
}

提前感谢您的指导!

【问题讨论】:

  • 抛出了什么异常?
  • 您可以查看该答案 (stackoverflow.com/questions/28264198/…),了解如何在 Web 容器环境中正确使用 JDBC。另外我必须注意,连接对象不是线程安全的,必须为每个请求检索 - 换句话说,它不能是静态的,否则您将遇到并发问题。

标签: java servlets jdbc


【解决方案1】:

你需要从 doGet 方法调用你的 main 方法。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ma​​in(null); }

我建议将 main 方法重命名为受保护的 void getDataFromDb() {..} 无需将其命名为 main 方法,因为您将其用作 servlet。

【讨论】:

    【解决方案2】:

    考虑这个修改后的示例,它实现了一个可作为应用程序和 servlet 运行的双向解决方案。

    退房

    • 在不同的目标流中重复使用查询方法
    • 使用 try-with-resource 关闭已使用的资源
    • 不要在多个线程之间重用连接

    代码如下:

    @WebServlet("/jdbc")
    public class jdbc extends HttpServlet {
    
        protected static void main(String[] argv) {
            //If called as application: Output goes to System.out
            queryTo(System.out);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //Set Content-Type
            response.setContentType("text/plain; charset=UTF-8");
            //If called as Servlet: Output into servlet response
            queryTo(new PrintStream(response.getOutputStream()));
        }
    
        private static void queryTo(PrintStream out) {
            // Use try-with-resource t o autoclose Connection, PreparedStatement and
            // ResultSet
            try (Connection con = connectionQuery();
                    PreparedStatement statement = con.prepareStatement("SELECT * from Music_Categories");
                    ResultSet result = statement.executeQuery()) {
    
                // Log to out
                out.println("DataBase table accessed");
                while (result.next()) {
                    String retrievedid = result.getString("name");
                    out.println(retrievedid);
                }
            } catch (Exception e) {
                //Exception to output stream as well
                e.printStackTrace(out);
            }
        }
    
        //Don't keep instances of that around but create fresh.
        //A connection pool might be a good idea
        protected static Connection connectionQuery() throws Exception {
            // Don't need to do this since JDBC 4.0
            // Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Remote DB connection established");
            return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/newschemam?useSSL=false", "root", "root");
        }
    }
    

    【讨论】:

    • 嗨@Jan,感谢您的回复。我尝试使用它,但它会导致 tomcat 无法启动并引发很多错误
    猜你喜欢
    • 2012-11-25
    • 2014-01-03
    • 2011-05-22
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2011-06-17
    • 2015-01-08
    相关资源
    最近更新 更多