Wannabe JavaGeek Wannabe JavaGeek - 1 year ago 72
MySQL Question

Select multiple files shown on JTable and download them from the MySQL database

I have written code for

to download selected files represented on a
from the MySQL database. I want it to download all selected files.Initially i was able to download one file at a time.now i have edited the code and it does nothing and returns no error. what could be wrong in the code.

How can I achieve this in my code?

My code:

private void jButtonDownloadActionPerformed(java.awt.event.ActionEvent evt) {

int BUFFER_SIZE = 4096;

try {
int[] selected_rows= jTable1.getSelectedRows();
for (int i = 0; i < selected_rows.length; i++){
if (i < selected_rows.length - 1 ) {
String tableClick=(jTable1.getModel().getValueAt(selected_rows[i],i).toString());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_certificate","root","");
String sql= "SELECT Cert, Cert_Name FROM certificate WHERE Cert_Code =?" ;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, tableClick);
ResultSet rs=pstmt.executeQuery();
String filename = rs.getString("Cert_Name");
Blob blob = rs.getBlob("Cert");
InputStream inputStream = blob.getBinaryStream();
String filePath ="C:\\Users\\User\\Downloads\\Documents\\"+filename;
OutputStream outputStream = new FileOutputStream(filePath);

int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);

JOptionPane.showMessageDialog(null,"file saved to Documents in your C folder.");
}}} }
catch (Exception e)

Answer Source

Finaly i got it. Many thanks to @Thompson. i need to use JTable.getSelectedRows() instead of JTable.getSelectedRow() then loop the array as shown:

       int[] selected_rows= jTable1.getSelectedRows();
         Object[] row= new Object[6];
         for (int i = 0; i < selected_rows.length;  i++){
             for (int r = 0; r < row.length;  r++){
        String tableClick=   (jTable1.getModel().getValueAt(selected_rows[i],r).toString());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download