javawebservletsapache-commonsapache-commons-fileupload

What is the error in blob submission to DB?


I'm trying to make insertions and updates of an image in DB, already in blob format.

public static boolean alterarLogo(int id, Blob logo) {
            String sql = "update conta set conta_logo = " + logo + " where conta_id = " + id;
            try (Connection conn = ConexaoDBGeral.abre()) {
                if (conn != null) {
                    try (Statement ps = conn.createStatement()) {
                        ps.executeUpdate(sql);
                        return true;
                    }
                }
            } catch (SQLException ex) {
                Logger.getLogger(ContaDAO.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
            return false;
        }

The code above throws as an exception: "improper qualified name (too many dotted names) :javax.sql.rowset.serialblob".In Db the column in question is of the type "oid".

The code where I get the blob:

        int idEmpresa=-1;
        SerialBlob blob = null;
        byte[] contents;
        try {
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String fileName = FilenameUtils.getName(item.getName());
                    InputStream file = item.getInputStream();
                    contents = IOUtils.toByteArray(file);
                    try {
                        blob = new SerialBlob(contents);
                    } catch (SQLException ex) {
                        Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    ContaDAO.alterarLogo(idEmpresa, blob);
                }
            }
        } catch (FileUploadException e) {

I am using Java, Servlets and JSPs, and PostGres. Where is the error?


Solution

  • A partial answer only.

    You are generating the SQL statement like this:

    String sql = "update conta set conta_logo = " + logo + 
        " where conta_id = " + id;
    

    Since logo is declared as a Blob you will be calling Blob.toString() when generating the SQL. The javadocs for Blob do not specify what the toString() method will do, but it is unlikely to render the Blob into something that makes sense in the SQL language. Based on the error message you are seeing, my guess is that it is actually rendering the object using Object::toString() which will include the actual class name for the Blob instance you are using at that point.