Insert picture to MySQL : Blob Binary Data JDBC « Database SQL JDBC « Java






Insert picture to MySQL

 
/*

Defining the Table: Oracle and MySql

create table MyPictures (
   id INT PRIMARY KEY,
   name VARCHAR(0),
   photo BLOB
);
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertPictureToMySql {
  public static void main(String[] args) throws Exception, IOException, SQLException {
    Class.forName("org.gjt.mm.mysql.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
    String INSERT_PICTURE = "insert into MyPictures(id, name, photo) values (?, ?, ?)";

    FileInputStream fis = null;
    PreparedStatement ps = null;
    try {
      conn.setAutoCommit(false);
      File file = new File("myPhoto.png");
      fis = new FileInputStream(file);
      ps = conn.prepareStatement(INSERT_PICTURE);
      ps.setString(1, "001");
      ps.setString(2, "name");
      ps.setBinaryStream(3, fis, (int) file.length());
      ps.executeUpdate();
      conn.commit();
    } finally {
      ps.close();
      fis.close();
    }
  }
}

           
         
  








Related examples in the same category

1.Read BLOBs data from database
2.Store BLOBs data into database
3.Demo Display Binary Data From Database
4.Materialize binary data onto client
5.Blob: JDBC deals with Binary Data
6.Inserting Image in Database Table
7.Blob and JDBC: Image
8.Blob: Image 2
9.Blob: image 3
10.Insert an Image
11.Retrieve an Image
12.Store and retrieve an object from a table
13.Read CLOBs data from database
14.Getting BLOB Data from a Database Table: how to retrieves bytes from a BLOB.
15.Store CLOBs data into database?
16.Getting and Inserting Binary Data into an Database Table