Latest Entries »

Tuesday, April 5, 2011

java insert and read image from mysql

Sometimes it may happen that we need to store a picture in some database table (MYSQL). At the beginning you should to create a table that will store our image data. Pictures and other binary files is kept in a BLOB data type inside table column. For this purpose we need to crate table.

CREATE TABLE IF NOT EXISTS `Images` (
  `ImageId` int(11) NOT NULL AUTO_INCREMENT,
  `Description` varchar(150) COLLATE utf8_polish_ci NOT NULL DEFAULT '-',
  `ImageData` blob NOT NULL,
  PRIMARY KEY (`ImageId`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci

And now to manipulate the database we use two methods:

    //Insert Image
    public void InsertImage(String description,FileInputStream fotos);
    //read image from table with specific id
    public  BufferedImage getMySqlPhoto(int ImageId);

public  BufferedImage getMySqlPhoto(int ImageId){
        BufferedImage BI = null;
        Statement S;
        ResultSet rs;
        String sqlStatement = "SELECT ImageData FROM Images WHERE ImageId = '"+ImageId+"'";
        try {
            S = con.createStatement();
            rs = S.executeQuery(sqlStatement);
            if (rs.next()){
                Blob image = rs.getBlob("ImageData");
                InputStream input = image.getBinaryStream();
                BI=ImageIO.read(input);
                // set read buffer size
                input.close();
            }
        }
        catch (SQLException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        return BI;
    }
    public void InsertIntoZdjecie(String Description,FileInputStream fotos)
    {
        String INSERT = "INSERT INTO Images(Description,ImageData) VALUES (?,?)";
        System.out.println(INSERT);
        PreparedStatement ps1;

        try {
            ps1 = con.prepareStatement(INSERT);
            ps1.setString(1, Description);
            ps1.setBinaryStream(2, fotos);
            ps1.executeUpdate();
        } catch (SQLException ex) {
            ex.printStackTrace();
            
        }
    }

Isn't it cute ? :-)

0 comments:

Post a Comment