数据库连接无法通过Servlet工作

时间:2016-02-18 17:34:48

标签: java servlets jdbc

我只是想在我的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");
        }
    }
}

提前感谢任何指导!

2 个答案:

答案 0 :(得分:0)

您需要从doGet方法调用main方法。

protected void doGet(HttpServletRequest request,HttpServletResponse response)抛出ServletException,IOException {        主要(空);     }

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

答案 1 :(得分:0)

考虑这个修改过的示例,实现了一个可以作为应用程序和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");
    }
}