如何使用Java从blob插入和检索pdf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22557202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:29:00  来源:igfitidea点击:

how to insert and retrieve pdf from blob using Java

javamysqljdbcblob

提问by Sam Ray

I am trying to build some Java code that uses JDBC to:

我正在尝试构建一些使用 JDBC 的 Java 代码:

1) Insert a PDF into a longblobcolumn of MySQL and the filename into a varcharcolumn.

1) 将 PDF 插入longblobMySQL 的一列,并将文件名插入一varchar列。

2) Retrieve a PDF using the filename (consider it is the primary key) and show it to the user.

2) 使用文件名(认为它是主键)检索 PDF 并将其显示给用户。

As is clear from above, my table has two columns:

从上面可以清楚地看出,我的表有两列:

filename  pdf_file 
--------  ---------
stock     stock.pdf 
kids      kid.pdf 

Here is the code that i have written:

这是我写的代码:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();
        String filename = f.getAbsolutePath();
        path = filename;
         newpath = path.replace('\', '/');
    }                                        


 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        try{
        File newpdf = new File(newpath);
        FileInputStream fis = new FileInputStream(newpdf);
        ByteArrayOutputStream baos= new ByteArrayOutputStream();
        byte[] buff = new byte[2048000];
        for(int readNum; (readNum=fis.read(buff)) !=-1 ; ){
            baos.write(buff,0,readNum);
        }

        userpdf=baos.toByteArray();


    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
 PreparedStatement pstmt = null;

        try{
             Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ppl","root","");
             String proj_name = JOptionPane.showInputDialog("Please enter name of the file");
             /*
             String insert = "INSERT INTO project VALUES ('" + login.admission + "','" + login.yr + "','" + proj_name + "','" + userpdf + "')";

             java.sql.PreparedStatement pst = con.prepareStatement(insert);
             pst.executeUpdate(insert);*/

             String sql = "INSERT INTO project"+"VALUES (?,?,?,?)";


        pstmt = (PreparedStatement) con.prepareStatement(sql);
        pstmt.setString(1, login.admission);
        pstmt.setString(2, login.yr);
        pstmt.setString(3, proj_name);
        pstmt.setBlob(4, userpdf); //This line has an error may be because of userpdf.Plz //suggest

        pstmt.executeUpdate();


        JOptionPane.showMessageDialog(null, "Saved");
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    } 

The problems I am facing are:

我面临的问题是:

  1. If I insert a PDF of 175 kb, the MySQL table shows that it's size is 10 or 11 bytes. Why is this happening?
  2. When I try to retrieve the PDF I get a message that it is corrupt. (I have not included retrieval code.)
  1. 如果我插入 175 kb 的 PDF,MySQL 表显示它的大小为 10 或 11 个字节。为什么会这样?
  2. 当我尝试检索 PDF 时,我收到一条消息,指出它已损坏。(我没有包含检索代码。)

Please explain using the above scenario as I am a newbie in Java. Why is it that my whole pdf is not going into mysql table?

请使用上述场景进行解释,因为我是 Java 新手。为什么我的整个 pdf 没有进入 mysql 表?

回答by Gord Thompson

For inserting the PDF file into the MySQL database the following code seems to work fine for me:

为了将 PDF 文件插入 MySQL 数据库,以下代码对我来说似乎工作正常:

File pdfFile = new File("C:/Users/Gord/Desktop/zzTest.pdf");
byte[] pdfData = new byte[(int) pdfFile.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(pdfFile));
dis.readFully(pdfData);  // read from file into byte[] array
dis.close();

String myConnectionString =
        "jdbc:mysql://localhost:3307/mydb";
dbConnection = DriverManager.getConnection(myConnectionString, "root", "whatever");
PreparedStatement ps = dbConnection.prepareStatement(
        "INSERT INTO project (" +
                "filename, " +
                "pdf_file " +
            ") VALUES (?,?)");
ps.setString(1, "testpdf");
ps.setBytes(2, pdfData);  // byte[] array
ps.executeUpdate();

回答by Herb21

you must declare a private variable of type

你必须声明一个私有类型的变量

Byte[](private byte[] usjerpdf = null;)and change your pstmt.setBlob(4, userpdf)to pstmt.setBytes(4, userpdf)and it will work fine.

Byte[](private byte[] usjerpdf = null;)并将您的更改pstmt.setBlob(4, userpdf)pstmt.setBytes(4, userpdf),它会正常工作。

回答by regie

File pdfFile = new File("D:sample.pdf");
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
byte[] pdfData = new byte[(int) pdfFile.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(pdfFile));
dis.readFully(pdfData);  // read from file into byte[] array
dis.close();

try{
    String sql =  "INSERT INTO project (filename, pdf_file) VALUES (?,?)";
    pst = conn.prepareStatement(sql);

    pst.setString(1, jTextField1.getText());
    pst.setBytes(2, pdfData);  // byte[] array
    pst.executeUpdate();

    JOptionPane.showMessageDialog(null, "Saved");
} catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

回答by Vaibhav

// I have an table Multipart which has blob column PDFFile // Below simple code works perfectly fine. I'm passing the list of Documents ID's

// 我有一个表 Multipart,它有 blob 列 PDFFile // 下面的简单代码工作得很好。我正在传递文档 ID 列表

    private boolean updateDocuments(List<Integer> list) {
    try {
        Connection con = App.getMySQLDBConnection();
        for (Integer id : list) {
            PreparedStatement stmt = con.prepareStatement("UPDATE Multipart set PDFFile=? WHERE ID=?");
            File file2 = new File(NEW_FILES_DIR + id.toString() + ".pdf");
            FileInputStream fis = new FileInputStream(file2);
            stmt.setBlob(1, fis);
            stmt.setInt(2, id);
            stmt.executeUpdate();
            stmt.close();
        }
        return true;
    } catch (Exception e) {
        System.out.println("Something Went Wrong! Please check stacktrace");
        e.printStackTrace();
    }
    return false;
}

private boolean createBackup(List<Integer> list) {
    System.out.println("Creating a backup of all " + list.size() + " Documents!");
    try {
        Connection con = App.getMySQLDBConnection();
        Statement stmt = con.createStatement();

        for (Integer id : list) {
            ResultSet rs = stmt.executeQuery("SELECT FileName, PDFFile FROM Multipart WHERE ID=" + id);
            while (rs.next()) {
                File file2 = new File(BACKUP_DIR + id + ".pdf");
                FileOutputStream fos = new FileOutputStream(file2);
                fos.write(rs.getBytes("PDFFile"));
                fos.close();
            }
        }
        return true;
    } catch (Exception e) {
        System.out.println("Something Went Wrong! Please check stacktrace");
        e.printStackTrace();
    }
    return false;
}