Read file via OutputStream from mysql - Java JDBC

Java examples for JDBC:MySQL

Description

Read file via OutputStream from mysql

Demo Code


import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.*;

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {//w  w  w .  j  av a 2 s  .c om
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Connection formed successfully");
            String myUrl = "jdbc:mysql://localhost/mydb";
            String pwd = "arijit";
            Connection con = DriverManager
                    .getConnection(myUrl, "root", pwd);
            long timeBefore = System.nanoTime();

            PreparedStatement ps = con
                    .prepareStatement("select * from attachment where name=?");
            long timeAfter = System.nanoTime() - timeBefore;

            jTextField2.setText("" + timeAfter);
            ps.setString(1, jTextField1.getText());
            ResultSet rs = ps.executeQuery();
            rs.next();
            Blob b = rs.getBlob(1);
            InputStream input = b.getBinaryStream();
            OutputStream o = new FileOutputStream("E:\\" + rs.getString(2));
            int bytesRead = -1;
            byte[] buffer = new byte[4096];
            while ((bytesRead = input.read(buffer)) != -1) {
                o.write(buffer, 0, bytesRead);
            }
            input.close();
            o.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

Related Tutorials