从数据库下载 BLOB 文件

StR*_*zZz 0 java database swing download jbutton

我需要创建一个JButton从 oracle 数据库下载 BLOB 文件。这是我的JButton代码:

JButton btnsave = new JButton("Save");
btnsave.setBounds(478, 542, 120, 23);
getContentPane().add(btnsave);
btnsave.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {


}
});
Run Code Online (Sandbox Code Playgroud)

这个类已经连接到数据库,但这是我的代码的一部分:

Connection con;


String link="*******************************************";
       String u="user";
       String p="pw";
       Class.forName("oracle.jdbc.driver.OracleDriver");
       conn=DriverManager.getConnection(link,u,p);


Statement su=con.createStatement();
Run Code Online (Sandbox Code Playgroud)

那么我怎样才能下载一个带有 的 blob 文件ActionListenerJButton?我还需要创建另一个语句吗?

提前致谢!

Alb*_*rto 5

您可以使用此代码(但我目前无法尝试)。query是查询,是子句index中的索引列SELECTfile是输出文件。

// take the result of the query
ResultSet rs = su.executeQuery(query);
while(rs.next()) { // for each row
   // take the blob
   Blob blob = rs.getBlob(index);
   BufferedInputStream is = new BufferedInputStream(blob.getBinaryStream());
   FileOutputStream fos = new FileOutputStream(file);
   // you can set the size of the buffer
   byte[] buffer = new byte[2048];
   int r = 0;
   while((r = is.read(buffer))!=-1) {
      fos.write(buffer, 0, r);
   }
   fos.flush();
   fos.close();
   is.close();
   blob.free();
}
su.close();
Run Code Online (Sandbox Code Playgroud)

同样,我目前无法尝试此代码。在确保它按照您想要的方式工作之前进行测试。