1

我有一个将 docx 文件存储到我的 MYSQL 数据库 MEDIUMBLOB 数据类型的程序。

如何从数据库中检索该文件,然后使用 APACHE POI 读取它以检查单词、段落等的数量?(最初的问题)

这是我保存文件的代码。

public void saveFile(String FileDirectory, String FileName)
{
    try {
        //Connecting to MYSQL Database
        Class.forName(driver).newInstance();
        con = DriverManager.getConnection(url+dbName,userName,password);

         //saving the image
        PreparedStatement psmnt = (PreparedStatement) con.prepareStatement("INSERT INTO doccompfiles VALUES(?,?,?)");
        psmnt.setInt(1, 5);
        psmnt.setNString(2, FileName);
        File f = new File(FileDirectory + FileName);
        psmnt.setBlob(3, new FileInputStream(f), f.length());
        psmnt.executeUpdate();

        con.close();
        }
    catch (Exception e) {
          JOptionPane.showMessageDialog(null, "Error saving file");
          e.printStackTrace();
     }

}

研究并找到了一种方法,但我的堆栈跟踪有错误。这是检索的代码。

public void loadFile(String FileName)
{
    try
    {
        //Connecting to MYSQL Database
        Class.forName(driver).newInstance();
        con = DriverManager.getConnection(url+dbName,userName,password);

        Statement stmt = (Statement) con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM doccompfiles WHERE FileName = '"+ FileName +"'");
        InputStream is = rs.getBinaryStream("File");

        HWPFDocument doc = new HWPFDocument(is);
        WordExtractor we = new WordExtractor(doc);

        String[] paragraphs = we.getParagraphText();
        JOptionPane.showMessageDialog(null, "Number of Paragraphs" + paragraphs.length);
        con.close();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

堆栈跟踪:

java.sql.SQLException: Before start of result set
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
    at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:854)
    at com.mysql.jdbc.ResultSetImpl.getBinaryStream(ResultSetImpl.java:1553)
    at com.mysql.jdbc.ResultSetImpl.getBinaryStream(ResultSetImpl.java:1586)
    at documentComparisor.Database.loadFile(Database.java:150)
    at documentComparisor.Home$5.actionPerformed(Home.java:195)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

我可以验证文件是否存储在数据库中,并且 select 语句中的表详细信息是否正确。有任何想法吗?

谢谢!

4

2 回答 2

1
  1. 从表中选择您的 BLOB(在处理大文件时查找 getBinaryStream,否则查找 getBlob)

  2. 处理它:

    HWPFDocument doc = new HWPFDocument(binaryStream);
    WordExtractor we = new WordExtractor(doc);
    
    String[] paragraphs = we.getParagraphText();
    System.out.println("Total Paragraphs: "+paragraphs.length);
    
    (then iterate through paragraphs array and count words)
    
于 2012-10-10T20:12:55.760 回答
0

请检查以下代码以从数据库中读取和写入 blob 数据

public class ReadBlobData {

    public static void main(String[] args) {
        writeBlob(65, "Test.docx");
        readBlob(65, "Test.docx");

    }

    public static void readBlob(int candidateId, String filename) {

        String selectSQL = "SELECT  document_text FROM scope1.documents where id=?";
        ResultSet rs = null;

        try (Connection conn = MySQLJDBCUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(selectSQL);) {
            // set parameter;
            pstmt.setInt(1, candidateId);
            rs = pstmt.executeQuery();

            // write binary stream into file
            File file = new File(filename);
            FileOutputStream output = new FileOutputStream(file);

            System.out.println("Writing to file " + file.getAbsolutePath());
            while (rs.next()) {
                InputStream input = rs.getBinaryStream("document_text");
                byte[] buffer = new byte[(int) file.length()];
                while (input.read(buffer) > 0) {
                    output.write(buffer);
                }
            }
        } catch (SQLException | IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static void writeBlob(int candidateId, String filename) {
        // update sql
        String updateSQL = "UPDATE scope1.documents " + 
                " SET  document_text=? WHERE id=?";

        try (Connection conn = MySQLJDBCUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(updateSQL)) {

            // read the file
            File file = new File("/home/hardik/Desktop/Test.docx");
            FileInputStream input = new FileInputStream(file);
            System.out.println(file.length());

            // set parameters
            pstmt.setBinaryStream(1, input);
            pstmt.setInt(2, candidateId);

            // store the resume file in database
            System.out.println("Reading file " + file.getAbsolutePath());

            pstmt.executeUpdate();
            System.out.println("Store file in the database.");

        } catch (SQLException | FileNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }

}



public class MySQLJDBCUtil {

    public static Connection getConnection() throws SQLException {
        Connection conn = null;

            // assign db parameters
            String url ="jdbc:mysql://localhost:3306/scope1" ;
            String user ="root" ;
            String password = "root";

            // create a connection to the database
            conn = DriverManager.getConnection(url, user, password);

        return conn;
    }

}
于 2019-08-14T11:15:15.077 回答