Insert file as to InputStream mysql - Java JDBC

Java examples for JDBC:MySQL

Description

Insert file as to InputStream mysql

Demo Code

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.Cursor;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import java.util.List;
import java.util.Set;
import javax.swing.JOptionPane;
import java.sql.*;
import java.io.*;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {//from  w w w.ja v  a2  s .c o m
            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);
            String query = "insert into attachment values(?,?)";
            PreparedStatement ps = null;
            ps = con.prepareStatement(query);
            InputStream inputStream = new FileInputStream(new File(
                    jFileChooser1.getSelectedFile().getPath()));
            ps.setBlob(1, inputStream);
            ps.setString(2, jFileChooser1.getSelectedFile().getName());
            long timeBefore = System.nanoTime();
            ps.execute();
            long finalTime = System.nanoTime() - timeBefore;
            jTextField2.setText("" + finalTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

Related Tutorials