如何测试DAO连接

时间:2015-04-19 14:35:13

标签: java mysql jdbc

我有一个mySql数据库,我正在使用phpMyAdmin来管理它。我编写了一个简单的JDBC DAO来测试它,但它不会返回任何数据。

我对DriverManager.getConnection函数使用的字符串进行了双重和三重检查,它们与我用于通过phpMyAdmin登录的字符串完全相同。

有没有更简单的方法来检查我的DAO是否可以实际连接,即在DAO本身内而不是像我正在使用的那样使用servlet?

//above this I have my imports, and username and password string
public Car getCar(int vin){
    Car c = null;
    Connection con = null;
    Statement stmt = null;
    try{
        con = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM carList WHERE vin=" + vin);
        if(rs.next()){
            c = new Car();
            c.setVin(rs.getInt(1));
            c.setMake(rs.getString(2));
            c.setMake(rs.getString(3));
            c.setYear(rs.getInt(4));
            c.setTransmission(rs.getString(5));
            c.setFuelType(rs.getString(6));
            c.setColour(rs.getString(7));
            c.setDoors(rs.getInt(8));
            c.setPrice(rs.getInt(9));
        }
    } catch (SQLException ex){

    } finally{
        try{
            if (stmt != null)
            {
                stmt.close();
            }
            if (con != null)
            {
                con.close();
            }
        } catch (SQLException ex){
            Logger.getLogger(carDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return c;
}

简单的servlet,用于返回数据库中特定汽车的某些信息。它将打印“细节”行,但没有别的。我也尝试过覆盖Car类中的默认toString方法。

//imports etc above here
public class DAOTester extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet DAOTester</title>");            
        out.println("</head>");
        out.println("<body>");
        carDAO dao = new carDAO();
        Car c = dao.getCar(35673451);
        out.print("details ");
        out.print(c.toString());
        out.println("</body>");
        out.println("</html>");
    }
}

0 个答案:

没有答案