简体   繁体   English

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

[英]how to insert and retrieve pdf from blob using Java

I am trying to build some Java code that uses JDBC to: 我正在尝试构建一些使用JDBC的Java代码:

1) Insert a PDF into a longblob column of MySQL and the filename into a varchar column. 1)将PDF插入MySQL的longblob列,并将文件名插入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. 如果插入175 kb的PDF,MySQL表将显示其大小为10或11个字节。 Why is this happening? 为什么会这样呢?
  2. When I try to retrieve the PDF I get a message that it is corrupt. 尝试检索PDF时,我收到一条消息,指出它已损坏。 (I have not included retrieval code.) (我没有包含检索代码。)

Please explain using the above scenario as I am a newbie in Java. 由于我是Java的新手,请解释使用上述方案。 Why is it that my whole pdf is not going into mysql table? 为什么我的整个pdf都没有进入mysql表?

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();

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) ,它将正常工作。

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);
}

// I have an table Multipart which has blob column PDFFile // Below simple code works perfectly fine. //我有一个表Multipart,其中有blob列PDFFile // //下面的简单代码可以很好地工作。 I'm passing the list of Documents ID's 我正在传递文档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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM