在eclipse中将Servlet连接到MySQL数据库

时间:2014-09-08 13:41:12

标签: java eclipse jsp servlets

我使用JDBC成功地将数据库与简单的java程序连接,但是当我尝试使用Servlet连接数据库时,它给出了以下错误和异常:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8888/ebookshop
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at QueryServlet.doGet(QueryServlet.java:35)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

所有服务器运行良好,我已经在我的库中添加了servlet和连接器API。

有关更多信息,这些是我的html和servlet文件:

html文件

<html>
    <head><title>Yet Another Bookshop</title></head>

    <body>
        <h2>Yet Another Bookshop</h2>
        <form method="get" action="http://localhost:9999/Sixth/query">
            <b>Choose an author:</b>
            <input type="checkbox" name="author" value="Tan Ah Teck">Ah Teck
            <input type="checkbox" name="author" value="Mohammad Ali">Ali
            <input type="checkbox" name="author" value="Kumar">Kumar
            <input type="submit" value="Search">
        </form>
    </body>
</html>

我的servlet:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

public class QueryServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // JDK 6 and above only
    // The doGet() runs once per HTTP GET request to this servlet.
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Set the MIME type for the response message
        response.setContentType("text/html");
        // Get a output writer to write the response message into the network socket
        PrintWriter out = response.getWriter();

        Connection conn = null;
        Statement stmt = null;

        try {
            // Step 1: Allocate a database Connection object
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
            // database-URL(hostname, port, default database), username, password

            // Step 2: Allocate a Statement object within the Connection
            stmt = conn.createStatement();

            // Step 3: Execute a SQL SELECT query
            String sqlStr = "select * from books where author = "
                    + "'" + request.getParameter("author") + "'"
                    + " and qty > 0 order by price desc";

            // Print an HTML page as the output of the query
            out.println("<html><head><title>Query Response</title></head><body>");
            out.println("<h3>Thank you for your query.</h3>");
            out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
            ResultSet rset = stmt.executeQuery(sqlStr);  // Send the query to the server

            // Step 4: Process the query result set
            int count = 0;
            while (rset.next()) {
                // Print a paragraph <p>...</p> for each record
                out.println("<p>" + rset.getString("author")
                        + ", " + rset.getString("title")
                        + ", $" + rset.getDouble("price") + "</p>");
                count++;
            }
            out.println("<p>==== " + count + " records found =====</p>");
            out.println("</body></html>");
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

4 个答案:

答案 0 :(得分:1)

您需要在获得连接之前加载驱动程序,如下所示:

//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

这是一个很好的例子:http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm

答案 1 :(得分:0)

你应该添加这一行,

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

因为这是与JDBC驱动程序建立连接的第一步,

Connection conn = null;
      Statement stmt = null;
      try {
              Class.forName("com.mysql.jdbc.Driver");
         // Step 1: Allocate a database Connection object
         conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
            // database-URL(hostname, port, default database), username, password

         // Step 2: Allocate a Statement object within the Connection
         stmt = conn.createStatement();

请在您的buidpath中添加mysql connector jar

答案 2 :(得分:0)

我看到这个jdbc:mysql://localhost:8888/ebookshop你已经将mysql的默认端口从3306更改为8888

如果你没有改变端口,只需使用3306作为mysql的端口

正如异常所说No suitable driver found显然意味着你没有 你的类路径中的mysql-connector-[version].jar如果你正在使用eclipse,只需将jar放在WEB-INF/lib下,如果你使用的是独立的tomcat,只需将驱动程序jar放在Tomcat的lib文件夹中

答案 3 :(得分:0)

试试这个

public static void connect() throws Exception {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    String url = "jdbc:mysql://localhost:3306/database_name?autoReconnect=true";
    c = DriverManager.getConnection(url,"root","123");
}

感谢名单..