数据库连接失败但以前工作正常

时间:2017-07-13 07:38:24

标签: database servlets web

package library;

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

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

@WebServlet("/Database")
public class Books extends HttpServlet {
    private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
      final String DB_URL="jdbc:mysql://localhost/library";

      //  Database credentials
      final String USER = "root";
      final String PASS = "asdfghjkl";

      Statement stmt;

      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

      out.println(docType +
         "<html>\n" +
         "<head><title>" + "DataBase" + "</title></head>\n" +
         "<body bgcolor = \"#f0f0f0\">\n" +
         "<h1 align = \"center\">" + "Books List" + "</h1>\n");
      try {
         // Register JDBC driver
         Class.forName(JDBC_DRIVER);

         // Open a connection
         Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

         // Execute SQL query
         stmt = conn.createStatement();
         String sql;
         sql = "SELECT * FROM books";
         ResultSet rs = stmt.executeQuery(sql);

         // Extract data from result set
         while(rs.next()){
            //Retrieve by column name
            int isbn  = rs.getInt("ISBN");
            String title = rs.getString("Title");
            // String author = rs.getString("Author");
            int quantity = rs.getInt("Quantity");
            // String category = rs.getString("Category");
            // String publisher = rs.getString("Publisher");
            String date = rs.getString("Date");

            //Display values
            out.println("ISBN: " + isbn + "<br>");
            out.println(", Quantity: " + quantity + "<br>");
            out.println(", Title: " + title + "<br>");
            out.println(", Author: " + date + "<br>");
         }
         out.println("</body></html>");

         // Clean-up environment
         rs.close();
         stmt.close();
         conn.close();
      }
      catch(Exception e)
      {out.println("Not done");}
   }
}

几天前工作正常。现在我不知道为什么不能正常工作。任何人都可以找到问题。

P.S。我的WAMP服务器已启动并运行,我有一个名为library的数据库和一个名为books的表,其中包含很少的记录。

0 个答案:

没有答案