1

テキスト ファイルを MySQL データベースに保存しようとしています。必要に応じてファイルに保存します。

ファイルを保存するには、次のようにします。

public void saveFile_InDB(File file)
{  
     try {

        String sql = "INSERT INTO sent_emails (fileName, time, clientName) values (?, ?, ?)";
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1, new Date().toString());
        statement.setString(2, new Date().toString());

        InputStream inputStream = new FileInputStream(file); 
        statement.setBinaryStream(3, inputStream);

        int row = statement.executeUpdate();
        if (row > 0) {
            System.out.println("File saved sucessfully.");
        }
        conn.close();

    } catch (SQLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

ファイルを取得して保存するには、次のようにします。

public void retrieveFile_fromDB()
{
     try {

         Statement stmt = (Statement) conn.createStatement();
         ResultSet res = stmt.executeQuery("SELECT * FROM sent_emails WHERE clientName='sally'");
         FileOutputStream fos = new FileOutputStream("file.txt");  

         if (res.next()) {

             Blob File = (Blob) res.getBlob("fileName");
             InputStream is = File.getBinaryStream();
             int b = 0;

             while ((b = is.read()) != -1) {
                 fos.write(b);   
             }

             fos.flush();

         }
     } catch (IOException e) {
         e.getMessage (); e.printStackTrace(); 
         System.out.println(e); 
     } catch (SQLException e) {
         e.getMessage (); e.printStackTrace(); 
         System.out.println(e); 
     }
}

ファイルの保存は機能しますが、取得して保存しようとすると、出力ファイルに何も保存されませんか?

4

2 に答える 2