2

我正在尝试将上传的文件保存在 MySQL 数据库中,如下所示:

String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");

InputStream inputStream = null; // input stream of the upload file

// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
    // prints out some information for debugging
    System.out.println(filePart.getName());
    System.out.println(filePart.getSize());
    System.out.println(filePart.getContentType());

    // obtains input stream of the upload file
    inputStream = filePart.getInputStream();
}

Connection conn = null; // connection to the database
String message = null;  // message will be sent back to client

try {
    // connects to the database
    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    conn = DriverManager.getConnection(dbURL, dbUser, dbPass);

    // constructs SQL statement
    String sql = "INSERT INTO image(image,firstName, lastName) values (?, ?, ?)";
    PreparedStatement statement = conn.prepareStatement(sql);

    if (inputStream != null) {
        // fetches input stream of the upload file for the blob column
        statement.setBlob(1, inputStream);
    }

    statement.setString(2, firstName);
    statement.setString(3, lastName);

    // sends the statement to the database server
    int row = statement.executeUpdate();
    if (row > 0) {
        message = "File uploaded and saved into database";
    }
} catch (SQLException ex) {
    message = "ERROR: " + ex.getMessage();
    ex.printStackTrace();
} finally {
    if (conn != null) {
        // closes the database connection
        try {
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    // sets the message in request scope
    request.setAttribute("Message", message);

    // forwards to the message page
    getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}

当我运行这个我得到一个错误是:

javax.servlet.ServletException: Servlet execution threw an exception

root cause

java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBlob(ILjava/io/InputStream;)V
    UploadServlet.doPost(UploadServlet.java:64)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

这个错误的原因可能是什么?输入字段名称是名字,姓氏和照片

4

2 回答 2

3

您应该使用 mysql-connector-java-5.1.7-bin.jar它来完成这项工作。

于 2015-02-06T09:46:21.580 回答
1

正如 giorgiga 在这篇文章中所说,它是您的 JDBC 驱动程序版本。要么更新它,要么使用旧版本的 setBlob。

编辑: 取自 giorgiga 的回答,以防万一链接失效。

AbstractMethodError 表示您的 JDBC 驱动程序的 PreparedStatements 没有实现 setBlob(int, InputStream, long)。

使用较旧的 setBlob(int, Blob) 或更新您的驱动程序(Connector/J 5.1 实现了 Jdbc 4.0,这应该是您对 setBlob(int, InputStream, long) 所需要的)

于 2013-04-06T19:59:07.930 回答