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

时间:2014-03-21 11:13:18

标签: java mysql jdbc blob

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

1)将PDF插入MySQL的longblob列,并将文件名插入varchar列。

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

如上所述,我的表有两列:

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

这是我写的代码:

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

我面临的问题是:

  1. 如果我插入175 kb的PDF,MySQL表显示它的大小为10或11个字节。为什么会这样?
  2. 当我尝试检索PDF时,我收到一条消息,说明它已损坏。 (我没有包含检索代码。)
  3. 请使用上面的场景解释,因为我是Java的新手。为什么我的整个pdf没有进入mysql表?

4 个答案:

答案 0 :(得分:1)

为了将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();

答案 1 :(得分:1)

您必须声明类型为

的私有变量

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

///我有一个表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;
}