4 Replies Latest reply on Nov 3, 2008 9:15 AM by 807589

    problem inserting image in blob in mysql

    807589
      here's my code :--


      package com.light.connet;

      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.PreparedStatement;
      import java.sql.ResultSet;
      import java.sql.SQLException;

      public class Blobsample {
      public static void main(String[] args) throws Exception, IOException, SQLException {
      Class.forName("com.mysql.jdbc.Driver");
      Connection conn = DriverManager.getConnection("jdbc:mysql://172.29.8.100:3306/lightspeed", "lightuser", "lightuser");
      String INSERT_PICTURE = "insert into image (id,title,content) values(?,?,?)";

      FileInputStream fis = null;
      PreparedStatement ps = null;
      try {
      //save image as blob
      conn.setAutoCommit(false);
      File file = new File("C://Documents and Settings/user/My Documents/My Pictures/yamaha-vmax-official-dash.jpg");
      fis = new FileInputStream(file);
      ps = conn.prepareStatement(INSERT_PICTURE);
      ps.setString(1, "0004");
      ps.setString(2, "blobsample");
      ps.setBlob(3, fis);
      // .setBinaryStream(3, fis, (int) file.length());
      ps.executeUpdate();
      conn.commit();

      //read back
      String SELECT_PICTURE = "select id, title, content from image";
      ps = conn.prepareStatement(SELECT_PICTURE);
      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
      //save blob as an image
      FileOutputStream fos = new FileOutputStream("C://Documents and Settings/user/My Documents/My Pictures/yamaha-vmax-official-dash.jpg");
      //String id = rs.getString(1);
      //String name = rs.getString(2);
      InputStream is = rs.getBinaryStream(3);
      byte[] buf = new byte[3000];
      int read = 0;
      while ((read = is.read(buf)) > 0) {
      fos.write(buf, 0, read);
      }
      fos.close();
      is.close();
      }

      } finally {
      ps.close();
      fis.close();
      }
      }
      }